Learn how to use Laravel relationships with where conditions to efficiently filter related data in your applications. Master Eloquent’s powerful where clauses within relationships to optimize your Laravel queries and improve database performance.
Sometime might be you need to add where condition with your relation model then you can simply use whereHas() as i provide bellow example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 app. You Can Learn Laravel Check If Relationship Data is Empty Example
Several days ago i had same situation when i used laravel relationship. need to use where condition like i need to get those users that country is “India”. so i write condition like as bellow example:
Laravel Relationship Where Condition Example
Example:
$users = User::whereHas('countries', function($q){
$q->where('name', '=', 'India');
})->get();
dd($users);
You can also pass dynamic variable inside the whereHas() like this way:
Example 2:
$search = 'India';
$users = User::whereHas('countries', function($q) use($search){
$q->where('name', '=', $search);
})->get();
dd($users);
I hope it can help you….