How to use whereHas with orWhereHas in Laravel
In this, tutorial we will learn How to use whereHas with orWhereHas in Laravel. We can use Laravel default eloquent wherehas than orwherehas when we used relationship in the Laravel application. Sometimes we require to use query wherehas in Laravel.
Also read: Laravel Eloquent whereNull() and whereNotNull() Query
I will give you an example of how to use whereHas and orWhereHas in the Laravel application.
Laravel whereHas is used to add more than two relations with the database model and you have to add where condition with both of that relation model.
Now, we have a User Model with records. When I create a new user at that time I have two more fields for state and country. I have State and Country master. And our requirement was when we search on the text box than records should compare with the state and country of both models. So, we at that time were required to use whereHas with orWhereHas in our application.
Also read: Laravel Eloquent whereNotBetween() Example
use App\Models\User; use Session; public function searchUser(Request $request) { $users = User::with(['state', 'country']); if ($request->has('name')) { $users = $users->whereHas('state', function($query) use ($request) { $query->where('name', $request->name); })->orWhereHas('country', function($query) use ($request) { $query->where('name', $request->name); }); $users = $users->get(); dd($users); } else { session()->flash('error', 'something went wrong!'); return redirect()->route('users.index'); } }