kossa's avatar
Level 20

Pagination under load function (eager loading)

Hi,

I'm building a Rest API, I have to return all categories, and under each category I want to retrieve 15 articles, I have 2 models Category and Article, my code is :

$categories = Category::where('somthing', $something)->get();

return $categories->load(['articles' => function($q) {
    $q->latest()->paginate()
}]);

The problem I get only 15 of first categorie : http://storage5.static.itmages.com/i/16/0726/h_1469520214_3761040_c927d11e1c.png

Thank you for help

0 likes
4 replies
d3xt3r's avatar

You need to understand how eager loading works...

$categories = Category::where('somthing', $something)->get();
return $categories->load(['articles']);

// Means Fetch all categories where something = $something
//Fetch all articles where category_id in (list of ids loaded above)

$categories = Category::where('somthing', $something)->get();

return $categories->load(['articles' => function($q) {
    $q->latest()->paginate()
}]);

// Means Fetch all categories where something = $something
//Fetch all articles where category_id in (list of ids loaded above) Limit x,y

Where do you see,fetch ... limit x,y per category being applied ???

kossa's avatar
Level 20

Thank you @d3xt3r, @pmall, so what's the solution to retrieve 15 articles for each category in one request ?

Please or to participate in this conversation.