cre8
cre8

Reputation: 13562

Query Builder with multiple entry points

I have different filters I want to use for my model, but they are all optional.

if($foo) {
    $model = Model::where('id', 1);
}
if($bar) {
   $model = $model->where('age', 3);
}

So this code will only run if the first statement will success.

$model = Model::where('id', '<>', -1);
if($foo) {
    $model->where('id', 1);
}
if($bar) {
   $model->where('age', 3);
}

This would work, but it's dirty :(

So is it possible to save the Model to a variabel so I don't have to make a static call inside all if statements?

Upvotes: 1

Views: 65

Answers (2)

Jari Pekkala
Jari Pekkala

Reputation: 887

https://laravel.com/api/5.4/Illuminate/Database/Eloquent/Model.html#method_query

https://laravel.com/api/5.4/Illuminate/Database/Query/Builder.html#method_when

Model::query()->when($foo, function ($query) {
    $query->where('id', 1);
})->when($bar, function ($query) {
    $query->where('age', 3);
});

Upvotes: 2

Jerodev
Jerodev

Reputation: 33186

You could make your filters in a where function, this will group them all together nicely.

For example:

$models = Model::where(function ($query) use ($request) {
    $query->where('id', '<>' -1);

    if ($request->has('id')
        $quer->where('id', $request->id);

    if ($request->has('age'))
        $query->where('age', $request->age);

})->get();

Upvotes: 1

Related Questions