Back to Blog
Laravel

Optimizing Database Queries in Laravel

ARAtiqur Rahman
March 5, 2024

The N+1 query problem is the silent killer of application performance. Here is how to identify and crush it in your Laravel apps.

Eager Loading Relationships

When accessing relationships in a loop, Laravel by default executes a query for each iteration. Eager loading solves this by fetching all related models in a single query.

// Bad: Executes 101 queries for 100 posts

BadController.php
$posts = Post::all();

foreach ($posts as $post) {
    echo $post->author->name;
}

// Good: Executes only 2 queries

GoodController.php
$posts = Post::with('author')->get();

foreach ($posts as $post) {
    echo $post->author->name;
}

Chunking Large Result Sets

If you need to process thousands of records, don't load them all into memory. Use chunk() to process them in small batches.

Job.php
User::chunk(200, function ($users) {
    foreach ($users as $user) {
        // memory usage remains stable
        $user->notify(new WelcomeEmail());
    }
});
LaravelDatabasePerformance

Command Palette

Search for a command to run...