I have a user profile and a user can have many products. I am currently eager loading the users products and I'm able to display the products on the users profile. However, I would like to be able to paginate the products if the user has more than 5 products. What would be the best way to do that? Thank you in advance for the help.
You can still do pagination with that. This is one of my sample projects and it works! In your case you only need to provide the products that are associated with the current user ;)
MoviesController.php
public function paginate()
{
return Movie::with(['actors', 'producer'])->paginate(5);
}
Movie.php
public function actors()
{
return $this->belongsToMany('App\Actor');
}
public function producer()
{
return $this->belongsTo('App\Producer');
}
@blackbird I think your method will paginate the movies. The original question translated to your scenario would be "Get film X along with the first 5 actors".
@gretschduojet If you want to paginate one of the relations then you can do either:
$user = User::with('UserNotes')->whereEmail($email)->firstOrFail();
$products = $user->productRegistration()->paginate();
// then pass both variables to the view
return View::make('some.view', compact('user', 'products');
// and loop through the products directly
@foreach ($products as $product)
or this - but this in fact only fetches portion of the related rows, and returns Collection, instead of Paginator, so it is not the way to go if you want to be able to render links using ->ProductRegistration->render().
$user = User::with(['UserNotes', 'ProductRegistration' => function ($q) {
$q->paginate();
}])->whereEmail($email)->firstOrFail();
@cyberomin Take a look at my answer above - I edited it with appropriate comment concerning render - you don't eager load with pagination if you want to render the links.