Lugi's avatar
Level 21

Constraining Eager Loads and Pagination

Here is my initial request for fetching 10 latest active posts:

$posts = Post::where('status', 'active')
     ->latest('updated_at')
     ->paginate(10);

I would like to do Eager Loading so I get posts with images. Later I'll pass that data to Controller.

How to do this Eager Loading but also do the pagination for 10 latest active posts ?

I tried to somehow combine with() and where() but I'm definitely doing something very very wrong :-)

Thanks.

0 likes
6 replies
Snapey's avatar
$posts = Post::with('images')
    ->where('status', 'active')
    ->latest('updated_at')
    ->take(10)
    ->get();
1 like
jlrdw's avatar

No such thing as eager loading with pagination it's automatic you are only retrieving so many at a time and you probably need to learn how to use the Skip and take. As it's not automatic you will have to work up skip and take variables. That is if later you plan on paginating more than just the 10 initial you retrieve.

Snapey's avatar

not sure why you would not be able to eager load and paginate.

if definitely not then $posts->load('images')after the pagination should do the trick

jlrdw's avatar

Eager loading just means getting all that you requested at the time no different than running two queries. I just don't get into the fancy terminology for loading data if you requested all of it at the time.

If paginating 10 then you are retrieving 10 at a time no different if you were using a single page app so why call it eagar loading.

1 like
Lugi's avatar
Level 21

This is the solution:

$posts = Post::with('images')
    ->where('status', 'active')
    ->latest('updated_at')
    ->paginate(10);

Please or to participate in this conversation.