In this tutorial, I will show you laravel eager loading with condition. In this example, I will use a one to many relation to show you laravel eager loading where clause. Assume we have a Post model and one post has many comments. We will fetch those comments that are not approved.
To create this condition inside with laravel, I will use the where clause to create a condition inside an eloquent relationship. So let's see the example code of laravel eloquent eager loading with condition:
Now let's see the controller code example:
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' => function ($query) {
$query->where('is_approved', false);
}
])->first();
}
}
Now see the output:
{
"id": 1,
"user_id": 1,
"title": "Maxime non architecto quia in corporis iusto odio beatae.",
"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"
}
]
}
Conclusion
Now we know laravel eager loading with condition. Hope this laravel eager loading where clause tutorial will help you to create condition inside with laravel