Display Single Category Posts With OctoberCMS

- 1 answer

I have table categories with fields - id, category.
I have table posts with fields - id, title, description.
I have pivot table with fields - category_id, post_id.

How can i create route that will show all posts from one category? I've tried:

Route::get('category/{id}', function($id) {
  $posts = Post::with(['image','category'])->where('', $id)->get();
  return $posts;

but I get unknown column error.



There are a couple ways you could solve this. I will show you the laravel way with the whereHas method. You can look at the documentation here. I have hardly used the with method so you might need to experiment but this is how I would do it.

$posts = Post::with('image')->whereHas('category', function ($category) use ($id) {
    $category->where('id', $id);

Why I think your query isn't working is because your ->where('category_id', $id) is being done directly on the Post model which doesn't have a category_id I bet. You don't get access to the pivot table fields from one of the relationship models. You can always look at the collection attributes by doing a die and dump; dd($posts).

Also a big tip to think about in the future is create/use explicit variables. Instead of using category/{id} use category/{categoryId}. This will save you a lot of headaches in the future. It will also save a lot of headaches for people who look at your code.