Performance: kill N+1
Spot with debugbar
Open any list page with Debugbar visible and read the query count. A page that shows twenty rows but runs forty queries is confessing: the loop loads relations one by one instead of up front.
Watch the count while you page through results. If the number grows with the list size, you found an N+1 - the fix in the next section takes one line.
Eager load
The with method loads relations before the loop starts, turning N+1 queries into exactly two: one for the list, one for all related rows. Same output on screen, a fraction of the database work.
$slow = Post::all(); foreach ($slow as $post) { echo $post->author->name . "\n"; } $fast = Post::with("author")->get(); foreach ($fast as $post) { echo $post->author->name . "\n"; }
Cache counts
Counts and totals rarely need fresh computation on every request. Cache them for a minute and serve the stored number, so a busy sidebar stops hammering the database for a digit that barely moves.
$count = Cache::remember("post-count", 60, function () { return Post::count(); }); echo $count;
Measure first
Optimize only what you measured. Note the query count and page time, change one thing, then compare. Guessing feels productive, but the Debugbar numbers are the only reviewer that never flatters.
Keep a tiny log of before and after numbers for every fix. Over a month those lines become proof of progress - and a habit that senior developers will notice.
Next: Modern Laravel tour
Article author: Arthur Isaev