Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent conditional where filter

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();
like image 292
さりげない告白 Avatar asked Nov 05 '14 05:11

さりげない告白


2 Answers

Since Laravel 5.2.27, you can use conditional clauses

For example:

->when($gender, function($query) use ($gender) {
        return $query->where('gender', '=', $gender);
      })
->get();
like image 62
Arne De Smedt Avatar answered Oct 21 '22 23:10

Arne De Smedt


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();
like image 37
Laurence Avatar answered Oct 21 '22 22:10

Laurence