Relationships Pagination
I have a model being returned from a controller. I eager load some relationships using 'with' like so.
$item = Item::with('reviews.user')
->withCount('reviews')
->where('volume_id',request()->get('volume_id'))
->first();
I would like to paginate the items reviews but have not been able to find a way. Is there a way to specifically paginate a relationship?
Use paginate instead of first.
Since you are calling first() at the end, maybe this way you can achieve it:
$reviews = Item::with('reviews.user')->firstWhere('volume_id',request()->get('volume_id'))->reviews()->paginate();
and you don't need withCount since the pagination already contains the total of the reviews.
@Nakov The thing is I also need the the Item specific information, not just solely the reviews. I just want to paginate the reviews relation
@Nakov Im getting this error
Call to a member function reviews() on null
Im assuming this is failing because firstWhere() is returning null, is there a way I can catch this error in the eloquent chain?
I have this
$a= Item::firstWhere('volume_id',request()->get('volume_id'));
if($a){
$item = Item::with('reviews.user')
->firstWhere('volume_id',request()->get('volume_id'))
->reviews()->paginate(2);
}
But it seems like this does not return Items but rather only the paginated relation (reviews).
@electric18 probably you need to custom your query to accept some parameters instead of use the pagination function provided by Laravel.
Solved
$item = Item::firstWhere('volume_id',request()->get('volume_id'));
if($item){
$reviews = $item->reviews()->with('user')->paginate(2)->withQueryString();
}
return('_',compact('item','reviews');
Please or to participate in this conversation.