Farhandev's avatar

Laravel pagination not working

hello

class Nested extends Model{
  public function nestedfunc()
{
    return $this->hasMany(Nested::class, 'parent_id');
}
 public function childnestedfunc()
{
    return $this->hasMany(Nested::class, 'parent_id')->with('nestedfunc');
}
}

//this is my model function for reccursion. how to add pagination to the root of the nested comments. i am storing all comments to the same table

root comment 1 -nested comments of root 1 .... root comment 2 - nested comments of root 2 .... paginate the root comments root comments 3 - nested comments of root 3 .... root comments 4 -nested commets of root 4..... paginate the root comments so on

0 likes
2 replies
gr_bl's avatar

If I'm not mistaken, pagination is made in the controller

tisuchi's avatar
tisuchi
Best Answer
Level 70

@farhandev

You don't need two separate functions here, relationships can recursively call themselves so first changes your relationships to this

public function children()
{
    return $this->hasMany(Nested::class, 'parent_id')->with('children');
}

Then for your query, you can just do

Nested::where('parent_id', null)->with('children')->paginate();

When I built a nested comments model I also added a scope to make it a little more readable

public function scopeTopLevel($query)
{
   return $query->where('parent_id', null);
}

So now the call in my controller is just

Comment::topLevel()->with('children')->paginate();
1 like

Please or to participate in this conversation.