Home > database >  How to do search in eloquent for inner tables in laravel
How to do search in eloquent for inner tables in laravel

Time:04-01

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

CodePudding user response:

you can constrain eager loading in this way:

Discover::with([
'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.

CodePudding user response:

You can do this If you want to filter from child table also

https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence

$discover = Discover::where('status', '1')
    ->where('name', 'LIKE', "%$searchString%")
    ->orWhereHas('category', function ($query) use ($searchString) {
        return $query->where('name','LIKE', "%$searchString%");
    })
    ->orderBy('created_at', 'DESC')
    ->get();

CodePudding user response:

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

  • Related