I use and recommend query scopes.
It keeps your code clean and readable while you can reuse code also.
In my model User
I would create a function called scopeFilter
public function scopeFilter($query, $params)
{
if(isset($params['status']) && trim($params['status']) !== '')
{
$query->where('status', '=', trim($params['status']));
}
if(isset($params['is_admin']) && is_bool($params['is_admin']))
{
$query->where('is_admin', '=', $params['is_admin'] ? '1' : '0');
}
return $query;
}
In my ApiUsersController
I would just use this call, note that word scope
is omitted when making the call.
public function index(Request $request)
{
$users = User::filter($request->all())->get();
return Response::make([
'success' => true,
'data' => $users
]);
}
Now in your case, you can have a loop in scopeFilter
something like following
foreach ($params as $key->$param) {
$query->where($key, '=', $param);
}
This is to give you an idea how I do it and it keeps the code clean.
Also please read Local Scopes in Laravel documentation here. IMHO it is cleanest way to achieve filtering.