user6780526
user6780526

Reputation:

Multi categories posts

I'm using laravel 5.6 and i have two tables categories and posts

I have created category_id in posts table which looks like

{id, category_id, title, description, created_at, updated_at}

I created a drop-down on the post create and edit form to select the category which works fine.

Now I am looking for something more advanced where a post can have multiple categories. I have changed belongTo to HasMany categories in post model.

I feel I am doing it the wrong way. Do i need to create another table i.e., post_categories

{id, category_id, post_id}

The reason i want to do this is because i have multiple posts which belong to multiple categories and my route is like this

site.com/categoryname/post-slug

So few posts appear in multiple categories.

Upvotes: 0

Views: 754

Answers (1)

Zach Robichaud
Zach Robichaud

Reputation: 325

You probably will need to use the pivot table. That way you can data mine. Even if you don't have a multi-select, you'll easily be able to collect posts linked to categories and vice versa. laraveldaily-good example. They use the sync method, one of my favs. when you save the form data you can just do something like App\Post::find($id)->categories()->sync(request()->input(categories')) and laravel will handle the rest for you.

Your relationships look like they are thought out. to me, it looks like your on the right track. Just use the belongsToMany relationship instead of HasMany

Laravel has great documentation on this: laravel many to many

Upvotes: 1

Related Questions