Eloquent conditional where filter

25,601

Solution 1

You could use a dynamic scope

class User extends Eloquent {

    public function scopeGender($query, $gender)
    {
        if ($gender) {
           return $query->whereGender($gender);
        }
        return $query;
    }
}

Then throughout your application

...->gender($gender)->get();

Solution 2

Since Laravel 5.2.27, you can use conditional clauses

For example:

->when($gender, function($query) use ($gender) {
        return $query->where('gender', '=', $gender);
      })
->get();
Share:
25,601
さりげない告白
Author by

さりげない告白

専門の無い開発者。 国籍の無い者。 大阪で色々な仕事をやっています。

Updated on April 23, 2021

Comments

  • さりげない告白
    さりげない告白 about 3 years

    If I have a variable that is optional, and I only want to have it search on it if it is defined, I know that I can do this, but is there a way to define the function elsewhere, so I don't need to rewrite the same anonymous function over and over again? Or are the any other good alternatives to going about solving this problem?

    .......->where(function($query) use ($gender){
                if ($gender) {
                    $query->where('gender', '=', $gender);
                }
                })->get();
    
  • Ogier Schelvis
    Ogier Schelvis over 3 years
    You are missing a return in front of $query->where('gender', '=', $gender);
  • Jason
    Jason over 2 years
    From Laravel 6, the closure function takes a second parameter, which provides the value that the when matched as truthy. So here $gender could be any expression, and the use ($gender) can be removed, to give: ->when(<expression>, function($query, $genderExpression) {...});