Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

istanbouly's avatar

Laravel recursively eager load relations to paginate them

Hello Guys,

there is a problem that I have been struggling with for too long time yes it is the eager loading but not just simple eager loading first I will provide the exact same scenario for my case then I will show you some of my attempts finally I will leave it to you to help me anyway thanks in advance.

I have three Models Post , Comment , Reply each eager loads the other in the exact same order so Post eager loads Comment and Comment eager loads Reply for eager loading I use the help of protected $with property on the model itself.

now what I am trying to accomplish is to limit the records returned for relations loading with eager loading so if I have 100 post each has 50 comments and each comment has 10 replies I want to paginate the data as follows :

5 posts each post has 10 comments and each comment has 3 replies this is what I was fighting for but I couldn't get it right

what I tired so far

I tried to use limit and take on the "hasMany" on my model but never worked correctly I also tried to specify the perPage protected property on each model but as I realize this has nothing to do with pagination during eager loading I also tried to pass closures in the with protected property as ASSOC format to add eager loading constraints but it didn't work.

I don't want to make the question any longer I think this would be clear if not then I am ready to provide and more required details.

Please help thank you guys.

0 likes
5 replies
istanbouly's avatar

Yes I tried that but $query->paginate instead of take but it only works for the first element in the pagination like the second post will have a key called comments but that would be empty array.

staudenmeir's avatar
Level 24

Thanks, @Snapey.

Yes, you can achieve this with my package: https://github.com/staudenmeir/eloquent-eager-limit

Use the HasEagerLimit trait in both the parent and the related model.

class Post extends Model {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}

class Comment extends Model {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}

Then you can apply limit()/take() to your relationships:

$posts = Post::with([
    'comments' => function ($query) {
        $query->limit(10);
    },
    'comments.replies' => function ($query) {
        $query->limit(3);
    }
])->paginate(5);
1 like
istanbouly's avatar

Thank you such and awesome package you just save my work thanks a lot appreciate it and thank to all of you guys

Please or to participate in this conversation.