Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel eloquent search on fields of related model

I have an eloquent models as,

User : users(id, username, password, email, status)

Profile : profiles(id, user_id, first_name, last_name, gender, dob)

In the controller logic, I am eagerly loading the Profile model.

I can do this,

$user = User::with('Profile')->get(); 

or

$user = User::with('Profile')->where('status', '1')->get(); 

but how to do something like,

$user = User::with('Profile')->where('status', '1')->where('gender', 'Male')->get(); 
like image 486
Dipendra Gurung Avatar asked Mar 07 '15 08:03

Dipendra Gurung


2 Answers

That's where whereHas comes in handy:

$user = User::with('Profile')->where('status', 1)->whereHas('Profile', function($q){     $q->where('gender', 'Male'); })->get(); 

Basically it adds the condition that the user needs to have a profile with gender = Male

like image 199
lukasgeiter Avatar answered Sep 19 '22 02:09

lukasgeiter


If you want to search multiple columns in relation model.

        $searchText = 'test text';         Product::with('owner')->where(function($query) use ($searchText)         {             $query->where('product_name', 'LIKE', '%' . $searchText . '%');              $columns = ['product_code', 'place_location', 'remark'];              foreach ($columns as $column ) {                 $query->orWhere($column, 'LIKE', '%' . $searchText . '%');             }              $query->orWhereHas('owner', function($q) use ($searchText) {                 $q->where(function($q) use ($searchText) {                     $q->where('name', 'LIKE', '%' . $searchText . '%');                     $q->orWhere('company_name', 'LIKE', '%' . $searchText . '%');                 });             });          }); 
like image 25
Marosdee Uma Avatar answered Sep 20 '22 02:09

Marosdee Uma