electric18's avatar

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?

0 likes
7 replies
jlrdw's avatar

Use paginate instead of first.

Nakov's avatar

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.

electric18's avatar

@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

electric18's avatar

@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?

electric18's avatar

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).

siangboon's avatar

@electric18 probably you need to custom your query to accept some parameters instead of use the pagination function provided by Laravel.

electric18's avatar
electric18
OP
Best Answer
Level 2

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.