Using WhereHas with orWhereHas () method in Laravel?

Spread the love

Hellow Buddies,

Here we learn how to use orwherehas in Laravel. We can eloquently use whereehas que or whereehas when using relation in the Laravel application. At some point we will have to use query or where in Laravel 6.

In this example, I’m going to show you how to use whereHas and orWhereHas in Laravel applications.

Often times we add more than two relationships to the database model, and you need to add the where condition with both relationship models than you would add the where condition with both models.

If you don’t understand clearly, I’ll explain with an example. I have a user model with some records. If I create a new user at this point, I’ll have two more fields for the city and state. I basically have a city and state teacher. I will add the affiliation to the relationship to my user model.

My requirement was a city and state search box. When I look in the text box, the records should be compared to the city and state, both models. So basically or condition with both relationship models. At this point, I need to use whereHas with orWhereHas in my application.

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);
}

I hope it could help you …

Thaaaank’s friends ….