How to do search in eloquent for inner tables in laravel

Viewed 70

I want to do filter in laravel eloquent for the inner tables, i have 3 tables, discover, category and subcategory, discover have category and subcategory id, if someone try to filter with any text name, i want to filter from all that 3 tables, i am not able to find, how to filter from category and subcategory table, here is my code, can anyone please help me to resolve this issue ?

$discover = Discover::with(['category','subcategory'])->where('status','1')->where('name','like',"%{$searchString}%")->orWhere('description','like',"%{$searchString}%")->orderBy('created_at', 'DESC')->get()->toArray();
3 Answers

you can constrain eager loading in this way:

Discover::with([
'category' => function($query){
          return $query->where('name','your-category-name'); 
       }
])->whereHas('category', function($query) {
          return $query->where('name','your-category-name'); 
       });

the same applies for other relationships. Further info can be found on the laravel docs.

has whereHas Or WhereRelation relation if you need OrderBY on relation tables then you need to do join

Related