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!
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...
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With