Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent
Last updated 2 years ago.
0

After reviewing your code, i am getting with below solution for you. whenever you try to submit the form for the post you will get the categories id into PostsController store method and in that you are already saving the post data. So, now you just have to write down 2 simple line of code .

After the line , "Post::create($data);" you need to fetch last inserted id of the post. lets say you get it in the variable $post_id. and in post lets for one of the category id you have selected from the form is $category_id = 1; so, considering that you can write,

line(1) - $post = Post::find($post_id); line(2) - $post->categories()->attach($category_id);

That's it, your relation of post with category is stored in pivot table category_post with $post_id and $category_id

Same way you can call line(2) for multiple categories for which same post is belongs. Let me know if anything is unclear in above explanation. I will get back to you soon.

Last updated 2 years ago.
0

Hey web-nirav i was with this problem too and your solution works, thanks!! But now, how can i use this into edit view? Show checked box and detech it.

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

saifulapm saifulapm Joined 19 May 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.