We already discussed laravel eager loading. We know how to eager load relationship data to overcome the n+1 problem. Now in this tutorial, we will see laravel lazy eager loading example. For eager loading, we do a query with a relationship in a single query. But for lazy loading, first, we fetch data and then we fetch the relationship along with the data.

Sometimes we may want to eager load a relationship after the parent model has already been fetched. For example, this may be useful if we want to dynamically decide whether to load related models:

laravel-lazy-eager-loading-example

See the example code of how to implement lazy loading in laravel:

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\User;

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

        return $post->load('posts.comments.replies');
    }
}

 

Now you will see the below nested relational data output like this:

{
    "id": 1,
    "name": "Candida Hickle I",
    "email": "jocelyn.murazik@example.net",
    "email_verified_at": "2023-01-15T04:59:17.000000Z",
    "status": "active",
    "created_at": "2023-01-15T04:59:17.000000Z",
    "updated_at": "2023-01-15T04:59:17.000000Z",
    "posts": [
        {
            "id": 1,
            "user_id": 1,
            "title": "Maxime non architecto quia in corporis iusto odio beatae. Harum cupiditate libero dicta et fuga vero. Autem facere id reprehenderit consectetur.",
            "is_published": 1,
            "created_at": "2023-01-15T04:59:18.000000Z",
            "updated_at": "2023-01-15T04:59:18.000000Z",
            "comments": [
                {
                    "id": 1,
                    "post_id": 1,
                    "comment": "Magnam quia aperiam velit fuga dolorem rerum.",
                    "is_approved": 0,
                    "created_at": "2023-01-15T04:59:18.000000Z",
                    "updated_at": "2023-01-15T04:59:18.000000Z",
                    "replies": [
                        {
                            "id": 1,
                            "comment_id": 1,
                            "reply": "Dolores aut consectetur itaque est aut.",
                            "created_at": "2023-01-15T04:59:18.000000Z",
                            "updated_at": "2023-01-15T04:59:18.000000Z"
                        }
                    ]
                }
            ]
        }
    ]
}

 

Read also: Laravel Eager Loading Nested Relationships Example

 

Conclusion

Now we know laravel eager loading vs lazy loading. Hope this laravel lazy loading example tutorial will help you to create how to implement lazy loading in laravel.