CamKem's avatar
Level 10

Paginating eloquent query when loading relationship

Hello, I am trying to work out how to paginate results (so that the results are formatted as threads.data, threads.links etc) where I am using load() to also grab the related user for a tread. This is the code I have, but it's not working:

        return Inertia::render('Discussion/Threads/Index', [
            'threads' => Thread::latest()->paginate(20)->load('user')
        ]);
0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To paginate the results while loading the related user for a thread, you can use the with method instead of load. Here's an example:

return Inertia::render('Discussion/Threads/Index', [
    'threads' => Thread::with('user')->latest()->paginate(20)
]);

This will load the related user for each thread and paginate the results. You can access the threads and pagination data in your view like this:

@foreach ($threads as $thread)
    {{ $thread->title }}
    {{ $thread->user->name }}
@endforeach

{{ $threads->links() }}

Please or to participate in this conversation.