Sometimes we need to create conditions inside eloquent relationships. Like we have a posts table and a post may have many comments. Now assume comments may have many replies. Now we would like to fetch only those replies whose comment_id is less than 5. How we can do that in laravel way?

This scenario is called laravel nested eager loading with condition if we create this query. So we need a where clause to create conditions inside the nested relationships in laravel. So you need to know the concept of laravel nested eager loading where clause. 

laravel-eloquent-nested-eager-loading-with-condition

Now let's see the example code of laravel eloquent nested eager loading with condition:

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\Post;

class TutorialController extends Controller
{   
    public function index()
    {   
        return Post::with([
            'comments:id,post_id,comment',
            'comments.replies' => function($query){
                $query->where('comment_id', '<', 5) ;
            }
        ])->first();
    }
}

 

Now see the output:

{
    "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.",
                "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 Eloquent Eager Loading With Condition

 

Conclusion

Now we know laravel nested eager loading with condition. Hope this laravel nested eager loading where clause will help you to create laravel load multiple relationship with condition.