Display Posts by Category in Laravel 8

Viewed 74

i have some issues that happen with my code for displaying posts by category.. Relation is one to many, post to category.. I can route to choosen category, but posts did not show..

Here's my Post Model:

public function category()
    {
        return $this->belongsTo(CategoriesPost::class);
    }

Category Model:

public function posts()
    {
        return $this->hasMany(Post::class, 'category_id');
    }

And here's my PostController

$posts = Post::where('article_status', 'published')->whereHas('category', function ($query) use ($slug) {
            return $query->where('category_slug', $slug);
        });

$category = CategoriesPost::where('category_slug', $slug)->first();

return view('pages.article', [
            'posts' => $posts,
            'category' => $category,
        ]);

I'm so sure my code was right, but why it didn't shows the posts, did anyone notice where's the problem of my code?

1 Answers

Rather than querying for the related Posts separately, why not access them via the relationship you have defined in your Category model? It will improve performance by reducing the number of calls to your database for a start.

So something like:

$category = CategoriesPost::with(['posts'])->where('category_slug', $slug)->first();

Then you can just access your posts relationship on the $category property in your view:

$category->posts;
Related