php – laravel BelongsToMany pagination-ThrowExceptions

Exception or error:

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('App\Category','parent_id','id') ;
public function parent()
    return $this->belongsTo('App\Category', 'parent_id','id');
public function posts(){

    return $this->belongsToMany('App\Post', 'category_post');
public function latestposts(){

    return $this->belongsToMany('App\Post', '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('App\Category', '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

How to solve:

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


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

Leave a Reply

Your email address will not be published. Required fields are marked *