Home > Software engineering >  Laravel get all posts from a category and all it's sub-categories
Laravel get all posts from a category and all it's sub-categories

Time:11-08

I try to do it via laravel-nestedset

Laravel 8

For example

Category model:

public function parent()
{
    $parent =  $this->belongsTo('Category', 'parent_id');
    return $parent;
}

public function children()
{
    $children = $this->hasMany('Category', 'parent_id');
    //$children->wherePublish(1);
    return $children;
}

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

I tested it with an example:

category1    //with 0 post in category1    
category1 > category2    //with 10 posts in category2    
category1 > category2 > category3      //with 5 posts in category3      

and I try to test it:

for //category1
$category->post()->get(); // return 0  post (I want 15 posts)

for //category2
$category->post()->get(); // return 10 posts (I want 15 posts)

for //category3
$category->post()->get(); // return 5 post  (I want 5 posts)

CodePudding user response:

Try this: for //category1

$category->posts; // return 0  post (I want 15 posts)

for //category2

$category->posts; // return 10 posts (I want 15 posts)

for //category3

$category->posts; // return 5 post  (I want 5 posts)

CodePudding user response:

It is possible to load ancestors and descendants using custom query, for example :

$category_id = 5;
$categories  = Category::descendantsAndSelf($category_id)
                 ->pluck('id')
                 ->toArray();

$posts = Post::whereIn('category_id', $categories)->get();

I explained the logic, but you can create a local scope on your model.

  • Related