Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Relational Query in Laravel Eloquent

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

like image 996
Rahul Reghunath Avatar asked Dec 05 '25 18:12

Rahul Reghunath


1 Answers

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();
like image 114
Alexey Mezenin Avatar answered Dec 08 '25 07:12

Alexey Mezenin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!