Laravel provides whereRelation() which is the almost same version of whereHas(). Assume a moment that we would like to query for a relationship's existence with a single, simple where condition statement than laravel whereRelation() is for you. Laravel where relation provides a simple and convenient way of checking relationship existence with the condition.
Laravel provides whereRelation
, orWhereRelation
, whereMorphRelation
, and orWhereMorphRelation
those helpers to check relationship existence with condition in a single statement like below:
Let's see the example query of laravel 9 where relation:
app/Http/Controllers/TutorialController.php
<?php
namespace App\Http\Controllers;
use App\Models\Post;
class TutorialController extends Controller
{
public function index()
{
return Post::whereRelation(
'comments', 'date', '<=', now()->subHour()
)->get();
}
}
Look at that, no need to pass a closure to check this condition like the eloquent with() method. 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"
}
]
Read also: Eager Loading With WhereHas Conditions In Laravel
Conclusion
Now we know laravel where relation Hope this laravel eloquent where relation example in laravel tutorial will help you to create laravel 9 where relation.