t0berius's avatar

laravel load() with pagination

Is there a way to use load() with a pagination? Code:

        case 'deposits':
            $user->load(['deposits' => function ($query) use ($request) {
                $query->latest();
            }])->paginate(15)->appends($request->input());
        break;

    return view('userProfile',[
        'user'    => $user,
    ]);

I've already tried both, including the paginate() method inside the anonymous function and outside, no success with both.

Idea is to load only the "requested" relations when a user profile is requested, section is specified inside request like:

/user/ID_OF_USER?section=deposits
0 likes
6 replies
Sinnbeck's avatar

I would set it on a seperate variable

case 'deposits':
            $deposits = $user->deposits()->latest->paginate(15)->withQueryString();
1 like
t0berius's avatar

@sinnbeck

whole view is already provided and expecting $user->deposits, I would like to keep this style, since it's quite easy to understand the naming.

Any other idea how to include the paginate() to my query above?

-Is withQueryString() exact the same as ->appends($request->input())?

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@t0berius Yes.

Ok then you can do

case 'deposits':
            $user->setRelation('deposits', $user->deposits()->latest->paginate(15)->withQueryString());
1 like
Snapey's avatar

i can't see anything wrong with your code? Are you sure its actually hitting this case?

Snapey's avatar

There is some confusion in the question as to whether you want paginated users or paginated deposits?

1 like
t0berius's avatar

@snapey always a pleasure to see your name here ;). Yes, it's hitting, I've used dd() to see the loaded object, it's:

relations: array:1 [▼
    "deposits" => Illuminate\Database\Eloquent\Collection 

So as you can see the object is incorrect, because of this it's returning:

Method Illuminate\Database\Eloquent\Collection::links does not exist.

I want to paginate the deposits, the user is always the same, since it's some kind of details page for a user.

Please or to participate in this conversation.