Question:
I went up on Github ( https://github.com/fabiojaniolima/larablog-beta ) a small project in Laravel, something very initial. I want to organize the routes, structure the methods, etc. as soon as possible.
I released this premature code because I ran into a problem that I'm not able to solve by myself. I explain below.
I set up a Categories scheme, this scheme will be used by the Library, Courses and Posts screen. I'm already managing to register the categories and also link a post to more than one category, as well as undo the relationship (post <=> category) when deleting the post. The problem is when editing a post, I'm not able to reassemble the entire structure of categories at the moment, pre-selecting those linked to the post.
The method used to edit the post is located at App\Http\Controllers\Panel\PostController:
public function edit(Post $post)
{
$categorias = Categoria::all()->toHierarchy();
return view('painel.posts.cad-edit', compact('post', 'categorias'));
}
I've known Laravel for a short time, so I don't know very well how it works. At the end of this project I will release it under an MIT license, as well as use this to make some of my books, articles and courses available for free.
The idea of categories is something like: imgur.com/a/itX71
Answer:
If you want to list the categories related to the post. You can call the model's method that tells you who the categories are associated with it.
Type:
public function edit(Post $post)
{
$categorias = Post::find($id)->categorias;
return view('painel.posts.cad-edit', compact('post', 'categorias'));
}
in this way it will return the categories related to this specific post!