1
votes

I want to paginate all my articles. 15 of them per page. Here is the call to paginate: Article::orderBy('created_at', 'desc')->paginate(15)

The pagination works fine but the problem is that on each article Laravel makes a query on my users table. 15 articles per page, 15 duplicate queries to my users table. Here is the image from debugbar: image source

How can I optimize the pagination and erase all those duplicate queries?

1
What relationship do you use between User and Article models? - Alexey Mezenin
In user model I have public function articles() { return $this->hasMany(Article::class); } and in articles I have public function user() { return $this->belongsTo(User::class); }. - ealocin

1 Answers

0
votes

You're using one-to-many relationship between these models, so to solve this problem (which is called N+1 query problem), use eager loading

Article::orderBy('created_at', 'desc')->with('user')->paginate(15)