Game Zen
Game Zen

Reputation: 25

how to add new category in post page laravel

when i want to make a post i have to first create a category on a different page, namely the category page, not the post page. how to make it like wordpress which can add categories and tags on the post page.

i have tried but i don't know how to make validation so that the category name and category slug (Str::slug) are unique.

after I tried to successfully add a category on the post page but when I added an existing category it still worked, not unique.

Same Category not unique

PostController.php

public function store(Request $request)
{
    $this->validate($request,[
        'name' => 'required',
        'categories' => 'required',
    ]);

    $slug = Str::slug($request->name);

    $post = new Post();
    $post->user_id = Auth::id();
    $post->name = $request->name;
    $post->slug = $slug;

    $post->save();

    // get old categories name
    $existingCategory = $video->categories->pluck('name')->toArray();

    // find new categories
    foreach($request->categories as $category) {
        if(! ( in_array($category, $existingCategory) ) ) {

            //create a new category
            $newCategory = new Category();
            $newCategory->name = $category;
            $newCategory->slug = Str::slug($category);
            $newCategory->save();
        }
    }

    $attachableCategory = [];

    foreach($request->categories as $category) {
        $attachableCategory[] = Category::where('name', $category)->pluck('id')->first();
    }

    $video->categories()->sync($attachableCategory);

    return redirect()->route('admin.post.index');
}

Upvotes: 1

Views: 376

Answers (1)

Manuel Glez
Manuel Glez

Reputation: 950

It seem that your categories are an array. I they are. Problably your are looking for array validation

Validator::make($input, [
     // validates there is an array 
    'categories' => 'required|array|min:1',  
     
     // validates values inside array
    'categories.*' => 'required|string|min:4'
]);

Upvotes: 1

Related Questions