How to use whereHas with orWhereHas in Laravel?
Here, we will learn how to use orwherehas in laravel. we can use eloquent wherehas than orwherehas when we used relationship in laravel application. some time we require to use query orwherehas in laravel 6.
In this example i will show you how to use whereHas and orWhereHas in laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 application.
Many time we add more than two relation with database model and you have to add where condition with both of that relation model than how you will add where condition with both model.
If you don't understand clearly than i will explain you by example. i have User Model with some records. When i create new user at that time i have two more fields for city and state. i basically i have City and State master. i will add belong to relationship with my User model.
Than my requirement was if i had one search box for city and state. when i search on text box than records should compare with city and state both model. So basically or where condition with both model relationship. At that time i require to use whereHas with orWhereHas in my application.
If you have same issue than you can see how i used simple whereHas with orWhereHas in my controller method. So let's see bellow code:
Example:
public function myUsers()
{
$users = User::with(['city', 'state']);
if ($request->has('name')) {
$users = $users->whereHas('city', function( $query ) use ( $request ){
$query->where('name', $request->name);
})->orWhereHas('state', function( $query ) use ( $request ){
$query->where('name', $request->name);
});
}
$users = $users->get();
dd($users);
}
you can use as bellow example.
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 Copy Record using Eloquent Replicate Example
- Laravel Eloquent Sum Multiple Columns Example
- Laravel Eloquent withMin(), withMax() and withAvg() Example
- Laravel Eloquent selectRaw() Query Example
- Laravel Eloquent Concat Two Columns Example
- Laravel Order By Relationship Sum Column Example
- Laravel Relationship Eager Loading with Condition Example
- Laravel Relationship Eager Loading with Count Example
- Laravel Relationship Where Condition Example
- Laravel Eloquent Relationships Tutorial From Scratch
- Laravel One to Many Eloquent Relationship Tutorial
- Laravel Many to Many Eloquent Relationship Tutorial
- Laravel One to Many Polymorphic Relationship Tutorial
- Laravel Many to Many Polymorphic Relationship Tutorial