How to retrieve categories linked to a post?

3

Uploaded to Github ( link ) a small project in Laravel, something very initial. I want as soon as possible to fix the routes, to structure the methods, etc.

I released this premature code because I came across a problem that I can not solve on my own. I explain below.

I've set up a Categories scheme, this scheme will be used by the Library, Courses and Posts screen. I am already able 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 at the moment of editing a post, I am not managing to reassemble the entire category structure by pre-selecting the ones linked to the post.

The method used to edit the post is located in App \ Http \ Controllers \ Panel \ PostController:

public function edit(Post $post)
{
    $categorias = Categoria::all()->toHierarchy();

    return view('painel.posts.cad-edit', compact('post', 'categorias'));
}

I know Laravel very soon, so I do not know his operation very well. At the end of this project I will release the same on an MIT license, as well as use this to make some of my books, articles and courses available for free.

The categories idea looks something like: imgur.com/a/itX71

    
asked by anonymous 12.04.2017 / 05:21

1 answer

0

If you want to list the categories related to the post. You can call the model method that tells you which 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'));
}

this way it will return the categories related to this post in specific!

    
19.04.2017 / 16:20