Raviya Technical
Published in

Raviya Technical

Laravel Eloquent Query | Laravel whereHas with orWhereHas

In this example, I will show you how to use whereHas and orWhereHas in laravel 6, laravel 7, and laravel 8 applications.

Many times we add more than two relations with the database model and you have to add where condition with both of that relation model than how you will add where condition with both models.

If you don’t understand clearly then I will explain to you by example. I have a User Model with some records. When I create a new user at that time I have two more fields for city and state. I basically have City and State master. I will add belong to a relationship with my User model.

Then my requirement was if I had one search box for city and state. when I search on text box then records should compare with city and state both models. 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 the same issue then you can see how I used simple whereHas with orWhereHas in my controller method. So let’s see bellow code:


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




PHP, Laravel And Flutter Development

Recommended from Medium

[Java][Greedy][LeetCode] Queue Reconstruction by Height #406

It’s dangerous to go alone!

Going serverless with React and AWS Amplify Part 2: Creating And Using Serverless Services

Hello connections, I am sooo excited to share my experience as an web intern at Let’s Grow More…

Alphr Weekly Report #18

How Lazy Evaluation Works in Ruby

4 Steps to Write Readable and Maintainable Functions

AWS Triggers on AWS CodeCommit

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Raviya Technical

Raviya Technical


More from Medium

Laravel Basic | Laravel 7/6 Resource Route and Controller Tutorial

Laravel 8 Authentication using Jetstream Example

Laravel 8 Authentication using Jetstream Example

How is Laravel work?

How Laravel work

Laravel 8 Create Custom Helper Function Example