Reputation: 682
I am trying to retrieve all rows in my table, but with user filters(where conditions).
Table looks like this:
news: id, category, type, body, is_active
I want the user to filter them by: type
and is_active
So i am using
if(Input::get("is_active"))
News::where("is_active", 1)->get();
if(Input::get("type"))
News::where("type", Input::get("type"))->get();
if(Input::get("category"))
News::where("category", Input::get("category"))->get();
How can I run all conditions on the same query? I don't want to make if/else for each condition and re-write the query all over again!
Upvotes: 0
Views: 4082
Reputation: 3026
You can pass a closure to where()
Try this:
$filters = ['is_avtive', 'type', 'category'];
News::where(function($q) use ($filters){
foreach($filters as $field)
$q->where($field, Input::get($field));
})->get();
Upvotes: 1
Reputation: 1234
Try this
News::where("is_active", 1)
->where('type', Input::get("type"))
->where('category', Input::get("category"))
->get();
or if you want only active news with other or conditions.
News::where("is_active", 1)
->orWhere(function($query)
{
$query->where('type', Input::get("type"))
->where('category', Input::get("category"))
})->get();
Check out advanced where
Upvotes: 1
Reputation: 87719
This way:
$query = News::newQuery();
if(Input::get("is_active"))
$query->where("is_active", 1)->get();
if(Input::get("type"))
$query->where("type", Input::get("type"))->get();
if(Input::get("category"))
$query->where("category", Input::get("category"))->get();
return $query->get();
Upvotes: 2