t0berius's avatar

eloquent pagination() for relation

Using this query:

            $user->load(['orders' => function ($query) {
                $query->with(['product:id,name'])->withTrashed()->latest();
            }]);

I would like to use a paginator for the retrieved orders.

How to do so? I know there's

$user->setRelation('orders', relation_query_here);

Any suggestions?

0 likes
3 replies
andreich1980's avatar

When I need pagination on relationship I do it like this

$orders = $user->orders()->paginate();
Snapey's avatar

You cannot do it with a nested relation.

Since you only have one user, pass the user and the orders as separate variables to the view, and paginate the orders.

@andreich1980 answer is the way

1 like
t0berius's avatar

Is this incorrect?

I've used:

            $user->setRelation('orders', $user->orders()->withTrashed()->with('product:id,name')->latest()->paginate(25));

Produces the correct SQL query.

Please or to participate in this conversation.