Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

JamesZimmerman's avatar

How to do search in eloquent for inner tables in laravel

I want to do filter in laravel eloquent for the inner tables, i have 3 tables, discover, category and subcategory, discover have omegle.2yu.co 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 https://omegle.love issue ?

$discover = Discover::with(['category','subcategory'])->where('status','1')->where('name','like',"%{$searchString}%")->orWhere('description','like',"%{$searchString}%") omegle.2yu.co->orderBy('created_at', 'DESC')->get(https://omglz.com)->toArray();

0 likes
3 replies
tykus's avatar

Use whereHas (or in this case orWhereHas) to constrain the query using the relationships:

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

Note I assumed both categories and subcategories table each have a name column that you want to filter on - change as appropriate. Also logical grouping of the OR constraints is necessary!

JamesZimmerman's avatar

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

Please or to participate in this conversation.