JorgeAnzola's avatar

How can get a collection of related models of a related model and paginate it?

Sorry if the title is not really clear, what I meant is: My user hasMany a parent models and each parent model has one child model, so if I do something with eager loading like

    $parents = Parent::with('child')
                 ->where('user_id', $user->id)
                 ->paginate($this->limit);

And my result would be something like:

{
    parent: {
        parent_property_1,
        parent_property_2,
        parent_property_3,
        CHILD
    },
    parent: {
        parent_property_1,
        parent_property_2,
        parent_property_3,
        CHILD
    }
}
pagination stuff

And what I really want is:

{
    CHILD,
    CHILD
}
pagination stuff

I also tried things like

    $user->parent
        ->load('child')
        ->paginate($this->limit);

But all I can get is a collection of parents with their children, and if I look into that collection, I don't know how to keep the pagination.

0 likes
2 replies
KrzysztofNiepokojczycki's avatar

How about


 $children = Child::whereHas('parent', function ($query) use ($userId) {
            return $query->where('user_id', $userId);
        })
            ->paginate($this->limit);
1 like

Please or to participate in this conversation.