PHP

Eager Load Eloquent Relationships to Optimize Queries

Optimize database performance by eager loading Eloquent relationships using the `with()` method to prevent common N+1 query problems in Laravel applications.

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index()
    {
        // N+1 problem example (avoid this for large datasets):
        // $users = User::all();
        // foreach ($users as $user) {
        //     echo $user->posts->count(); // Each $user->posts triggers a new query
        // }

        // Eager loading posts relationship to prevent N+1 queries
        $users = User::with('posts')->get();

        foreach ($users as $user) {
            echo "User: " . $user->name . ", Posts: " . $user->posts->count() . "
";
        }

        // Eager loading multiple relationships and nested relationships:
        $usersWithComments = User::with(['posts', 'posts.comments'])->get();

        foreach ($usersWithComments as $user) {
            echo "User: " . $user->name . ", Posts: " . $user->posts->count() . ", Comments on first post: " . ($user->posts->first() ? $user->posts->first()->comments->count() : 0) . "
";
        }

        return response()->json($users);
    }
}
How it works: This snippet demonstrates how to use Eloquent's `with()` method for eager loading relationships. Eager loading retrieves all related models for a given query in a single, efficient query, eliminating the 'N+1 query problem'. Without eager loading, accessing a relationship (e.g., `$user->posts`) inside a loop would execute a separate query for each parent model, leading to poor performance. The `with()` method accepts relationship names (e.g., 'posts') or nested relationships (e.g., 'posts.comments') to optimize data retrieval.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs