Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including a clause in an Eloquent query only if variable exists

I have a page that pulls GET request data.

So I have: example.com/page?filter1=1&filter2=false

Depending on the request, sometimes there may be a filter3 or filter4 or any combination of a number of 'filters'.

In my controller doing an Input::all(); and then wish to query my model/database.

For example: User::where('filter1', '=' , Input::get('filter1'));

That's just an example. How do I add to that query dynamically depending on which filters exist in the GET request?

These filters will be filtering data, and I want all the returned rows to include all of these filters.

Any help would be appreciated!

Thanks!

like image 269
KriiV Avatar asked Dec 14 '22 15:12

KriiV


2 Answers

If the filters are named exactly like the db fields, you can just pass them as array to where().

I recommend using except() so you have control over the filtered attributes.

$filters = Input::except('filter1', 'filter2', 'filter3');
$users = User::where($filters)->get();

If the filter names don't always match or you need a different operator than = you can add where's conditionally like this:

$query = User::where('foo', 'bar');
if(Input::has('one')){
    $query->where('filter1', '>', Input::get('one'));
}
$users = $query->get();

And if you have no unconditional where and need something "to start with" you can just use query() for that:

$query = User::query();
// add wheres...
like image 50
lukasgeiter Avatar answered Dec 25 '22 11:12

lukasgeiter


You can dynamically add all the where()-s to your query and after done building the query just use the get() to get corresponsing collections.

$query=User::where(where("filter1", Input::get("filter1"));
if(Input::has("filter2")) {
  $query=$query->where("filter2", Input::get("filter2"));
}
$users=$query->get();
like image 29
Margus Pala Avatar answered Dec 25 '22 09:12

Margus Pala