Skip to content
Advertisement

laravel BelongsToMany pagination

i have 2 model

1 – category with parent and child

class Category extends Model
{


protected $primaryKey = 'id';
public $fillable = ['slug','title','icon','parent_id'];
/**
 * Get the index name for the model.
 *
 * @return string
*/
public function childs() {
    return $this->hasMany('AppCategory','parent_id','id') ;
}
public function parent()
{
    return $this->belongsTo('AppCategory', 'parent_id','id');
}
public function posts(){

    return $this->belongsToMany('AppPost', 'category_post');
}
public function latestposts(){

    return $this->belongsToMany('AppPost', 'category_post')->latest()->limit(3);
}


}

2 – post model with belongsToMany->Category

class Post extends Model 
{

protected $primaryKey = 'id';
public $fillable = ['user_id','slug','title','excerpt','content','keyword','img','status'];

protected $table = 'posts';


public function cat_posts(){
    return $this->belongsToMany('AppCategory', 'category_post');

}


}

example data treeview:

1-category parent 

 |- 1-child category -> with 5 post

 |- 2-child category -> with 3 post

Now, when viewing the main section -> (category parent), I want to display all the posts in all of the children’s category To be the result of the number of posts = 8

And by pagination How can I do that

Advertisement

Answer

first, you need to make a query to get all subcategory from your main category

in this example, I suppose that the first category is a main category

$subsCat = Category::first()->childs->pluck('id');

after that you can fetch all products with these categories id

Post::whereIn('category_post', $subsCat)->paginate(8);

and in case if you don’t need to paginate you can make it in a single line using each from laravel collection like this one

$cat->childs->each(function($child){ 
   $child->posts;
})

you can read more about each and whereIn from the docs

The first example with paginate is more efficient because it will make only two queries

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement