babai9's avatar

How to create pagination in eager loaded relationship in laravel

I want the pagination to happen in eager loaded relation but when I am using it I am getting an error. Method Illuminate\Database\Eloquent\Collection::links does not exist. This only happens when I use {{ $SubjectReport->reports->links() }} in views rather than that everything is working fine as when I remove this {{ $SubjectReport->reports->links() }} the page loads with the number set in paginate method.

This is what I have tried so far

Here is my controller

$SubjectReport = Subject::with(['assesment.curriculumUnit',
    'reports' => function($q) {
    $q->orderBy('id','DESC')->paginate(2);
}])->where('id',2)->first();
 
return view('learner.assesment_reports',compact('SubjectReport'));

Here is my view

@foreach ($SubjectReport->reports as $key => $report)

@endforeach

{{ $SubjectReport->reports->links() }}

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

The issue is that the paginate() method returns a LengthAwarePaginator instance, but when you eager load the relationship, it returns a Collection instance. To solve this issue, you can use the paginate() method on the relationship query instead of the eager loading query. Here's an updated version of the controller code:

$SubjectReport = Subject::with(['assesment.curriculumUnit', 'reports'])
    ->where('id', 2)
    ->first();

$reports = $SubjectReport->reports()->orderBy('id', 'DESC')->paginate(2);

return view('learner.assesment_reports', compact('SubjectReport', 'reports'));

And in the view, you can loop through the $reports variable instead of the $SubjectReport->reports relationship:

@foreach ($reports as $key => $report)
    // display report data
@endforeach

{{ $reports->links() }}

Please or to participate in this conversation.