简体   繁体   中英

Display Posts by Category in Laravel 8

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM