I have build a filter on my database query and now I want to make it more comfortable. The goal is to make it dynamic that mean's the user has the option to combine as many as he wants.
public function filter(FilterList $request)
{
$view = view('profile.browse.list');
$search = $request->get('filter');
$filter = [
'male' => Profile::male(),
'female' => Profile::female(),
'10' => Profile::man(),
'11' => Profile::women(),
'12' => Profile::couple(),
'15' => Profile::domina(),
'20' => Profile::affaire(),
'21' => Profile::cybersex(),
'22' => Profile::marriage(),
'23' => Profile::flirt(),
];
return $view->with([
'List' => $filter[$search]->unmoderated()->paginate(15)->appends(['filter' => $search]),
]);
}
I know that my solution is not really a good solution. I have saved the query scopes in the $filter array and can not add a a second or thired scope like this
$users = User::popular()->women()->orderBy('created_at')->get();
http://laravel.com/docs/5.0/eloquent#query-scopes
Have anyony hint's for me for making it better.
I have no idea to start ...
Thanks for any help
Edit
public function scopeMarriage($query)
{
return $query->where('LookFor', 'LIKE', '%Ehe%');
}
So, the user is submitting a dynamic number of inputs, and based on those inputs, you want to keep chaining query scopes onto your query? If that's what you want, I believe you can do something like this this:
// Method array taken from your example
$methods = [
'male' => 'male',
'female' => 'female',
'12' => 'couple',
];
// Begin the query. Since the unmoderated() scope query is always called,
// I used that in this example.
// But note that you can also use Model::query(); to begin a query
$query = Profile::unmoderated();
// Loop through the request inputs
foreach ($request->all() as $param)
{
// If it exists in the provided array, add it to the query.
if (array_key_exists($param, $methods))
{
$query->{$methods[$param]}();
}
}
// Call get, paginate, etc. to actually fetch the results and then return it.
return $query->paginate(15);