Laravel provides eager loading to process our relationship data to avoid N+1 query problems. This eager loading optimizes our query performance and also optimizes our application loading time cause it reduces the execution time of a relational query if you use eager loading. I will use laravel eager loading one to many as an example in this tutorial.

Okay, in this tutorial, I will show you laravel eager loading example. I will use Post and Comment model and table to show you this laravel eager loading relationship tutorial example. Did you know that, when we access Eloquent relationships as properties, the related models are "lazy loaded" by default? This means the relationship data is not actually loaded until we first access the property. 

laravel-9-eager-loading

Look at that example without eager loading:

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Book extends Model
{
    /**
     * Get the author that wrote the book.
     */
    public function author()
    {
        return $this->belongsTo(Author::class);
    }
}

 

Now let's see how we can print every author of a book:

<?php

use App\Models\Book;
 
$books = Book::all();
 
foreach ($books as $book) {
    echo $book->author->name;
}

 

This above example is without eager loading. This example will create N+1 query problem and create a bad performance for our query and page loading time.

Eloquent Eager Loading Example

Now look at that, we will create eager loading with Post and Comment model. Look at our Post model:

app\Models\Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Post extends Model
{
    use HasFactory;

    public function comments() : HasMany
    {
        return $this->hasMany(Comment::class);
    }
}

 

And update the comment model like:

app\Models\Comment.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Comment extends Model
{
    use HasFactory;

    public function replies() : HasMany
    {
        return $this->hasMany(Reply::class);
    }

    public function post() : BelongsTo
    {
        return $this->belongsTo(Post::class);
    }
}

 

Now if we fetch data like this:

app\Http\Controllers\TutorialController.php

<?php

namespace App\Http\Controllers;

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

class TutorialController extends Controller
{   
    public function index()
    {   
        $post = Post::find(1);

        return $post;
    }
}

 

Look at that the output:

{
 "id": 1,
 "user_id": 1,
 "title": "Laudantium facere ad nihil eos consequatur et",
 "is_published": 1,
 "created_at": "2023-01-12T05:10:51.000000Z",
 "updated_at": "2023-01-12T05:10:51.000000Z"
}

 

Now fetch this data with eager loading. Like we want to fetch all comments on this post. To see the query with eager loading which removes N+1 query problem:

app\Http\Controllers\TutorialController.php

<?php

namespace App\Http\Controllers;

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

class TutorialController extends Controller
{   
    public function index()
    {   
        $post = Post::with('comments')->find(1);

        return $post;
    }
}

 

Read also: Laravel 9 Many To Many Polymorphic Relationship Example

 

Look at that the output:

{
    "id": 1,
    "user_id": 1,
    "title": "Laudantium facere ad nihil eos consequatur et. Voluptatem et commodi necessitatibus. A sunt voluptatem fugit occaecati recusandae est nobis.",
    "is_published": 1,
    "created_at": "2023-01-12T05:10:51.000000Z",
    "updated_at": "2023-01-12T05:10:51.000000Z",
    "comments": [
        {
            "id": 1,
            "post_id": 1,
            "comment": "Vitae repellat quod ut aut consectetur.",
            "is_approved": 0,
            "created_at": "2023-01-12T05:10:51.000000Z",
            "updated_at": "2023-01-12T05:10:51.000000Z"
        },
        {
            "id": 2,
            "post_id": 1,
            "comment": "Est et atque et illo magni cum et.",
            "is_approved": 0,
            "created_at": "2023-01-12T05:10:51.000000Z",
            "updated_at": "2023-01-12T05:10:51.000000Z"
        },
        {
            "id": 4,
            "post_id": 1,
            "comment": "Perferendis et corrupti quidem maiores autem est nulla.",
            "is_approved": 0,
            "created_at": "2023-01-12T05:10:51.000000Z",
            "updated_at": "2023-01-12T05:10:51.000000Z"
        },
        {
            "id": 7,
            "post_id": 1,
            "comment": "Quo omnis distinctio repellendus repellat velit.",
            "is_approved": 0,
            "created_at": "2023-01-12T05:10:51.000000Z",
            "updated_at": "2023-01-12T05:10:51.000000Z"
        },
        {
            "id": 11,
            "post_id": 1,
            "comment": "Quibusdam beatae possimus nulla.",
            "is_approved": 0,
            "created_at": "2023-01-12T05:10:51.000000Z",
            "updated_at": "2023-01-12T05:10:51.000000Z"
        }
    ]
}

 

Now show this data in your blade like:

resources/views/welcome.blade.php

<?php

$post->title;
 
foreach ($post->comments as $comment) {
    echo $comment->comment;
}

 

Recommended: Laravel One To One Polymorphic Relationship Example

 

Conclusion

I have tried to discuss the clear concept of laravel 9 eager loading. Hope this laravel eloquent eager loading tutorial will help you to optimize your query and hope now we will know what is eager loading in Laravel?