Currently I have the following search form to filter pagination result on the blade file:
<form method="get" >
<input name="search" id="search" type="text">
<button type="submit">Search</button>
</form>
And the query in the controller:
$search = $request->input('search');
$users = User::when($search, function ($query, $search) {
$query->where('name', 'like', "%$search%")->orWhere('email', 'like', "%$search%");
})->paginate(15)->withQueryString();
Now I want to add another filter as checkbox, for the example if would be filter for age, so display any result for someone who is "adult", or 18+. This is what I did and it works, however it doesn't seem right:
// added the checkbox
<form method="get" >
<input name="search" id="search" type="text">
<input type="checkbox" id="adult" name="adult" value=true>
<button type="submit">Search</button>
</form>
then added another when to the controller:
$search = $request->input('search');
$users = User::when($search, function ($query, $search) {
$query->where('name', 'like', "%$search%")->orWhere('email', 'like', "%$search%");
})->when($is_adult, function ($query, $search) {
$query->where('name', 'like', "%$search%")->orWhere('email', 'like', "%$search%")->where('age', '>', 18);
})->paginate(15)->withQueryString();
Looks too repetitive but couldn't make it work in another way. And now if I want to add more checkboxes it makes no sense to just copy paste same the same when() lines with the change being the filter itself