3

I have a search form which has dynamic filters and I want to generate relational queries dynamically based on the presence of the different filter.

using whereHas like

$properties = PropertyList::where('varification_status', '1')
    ->whereHas('common_property_details', function ($query) {
        $query->where('no_bathroom', '=', '1');
    })->get();

How do I populate dynamic queries without using a bunch of if else statements

Alexey Mezenin's answer is correct and have one more doubt. Now I can use

$properties = PropertyList::where('varification_status', '1')
                ->when($request['bathRooms'] > 0, function ($q) {
                    $q->whereHas('common_property_details', function ($query) {
                    $query->where('no_bathroom', '1');
                    });
                })->get();

but I can't use any varible inside query inside whereHas

I tried this

$properties = PropertyList::where('varification_status', '1')
            ->when($request['bathRooms'] > 0, function ($q) {
                $q->whereHas('common_property_details', function ($query,$bathRoom) {
                    $query->where('no_bathroom', $bathRoom);
                });
            })->get();

but showing the blow error

Missing argument 2 for App\Http\Controllers\PropertySearchController::App\Http\Controllers{closure}()

1 Answer 1

2

If you don't want to use a lot of if statements, you can use the when() method:

$properties = PropertyList::where('varification_status', '1')
    ->when($something === $somethingElse, function($q) {
        $q->whereHas(....);
    })
    ->when($something > $someMaximum, function($q) {
        $q->whereHas(....);
    })
    ->get();
Sign up to request clarification or add additional context in comments.

1 Comment

@RahulReghunath you need to use use() to pass a variable into a closure scope. For example whereHas(function($q) use($bathRoom) { .... })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.