Laravel Relationship Where Condition Example
Laravel 5 provide great feature as model relationship. but if you need to use where clause on your relation model then how you can do it?, You can make where condition using whereHas function. it doesn't matter which relation you used like one to one, one to many, many to many, has many through etc.
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.
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:
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....
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Eloquent inRandomOrder() Method Example
- Laravel Eloquent whereBetween() Query Example
- Laravel Eloquent Order By Query Example
- Multiple orWhere Condition in Laravel Eloquent
- Laravel Eloquent exists() and doesntExist() Example
- Laravel Eloquent orWhere() Condition Example
- Laravel Comment System Tutorial Example
- How to use Union Query with Laravel Eloquent?
- Laravel Eloquent Relationships Tutorial From Scratch
- Laravel One to One Eloquent Relationship Tutorial
- Laravel One to Many Eloquent Relationship Tutorial
- Laravel One to Many Polymorphic Relationship Tutorial
- Laravel Many to Many Polymorphic Relationship Tutorial
- Laravel Eloquent Order By Random Row Example