In Laravel, you can use the where
condition on relationships to retrieve related models that meet specific criteria. Here’s an example of how to use the where
condition in Laravel relationships:
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 below 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:
$search = 'India';
$users = User::whereHas('countries', function($q) use($search){
$q->where('name', '=', $search);
})->get();
dd($users);
It can help you!!!