Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ligonsker's avatar

Adding checkbox filters on top of text search box to pagination

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

0 likes
3 replies
sr57's avatar

makes no sense to just copy paste same the same when()

why ?

Different criteria need different when.

If you want you can put all you criteria in an array and use a loop to create your query it'll not make your code more readable and not your query faster.

1 like
Ligonsker's avatar

@sr57 Yep, they are quite different so I guess that does make sense

But I thought maybe my query in general looks odd. Could I somehow optimize it? Or it looks alright? And is it the right way chaining whens?

sr57's avatar

@Ligonsker

When is a laravel/php syntax above sql that makes you to have different queries regarding your parameters. It does not impact at all teh performance of underlying queries and there is no order preference.

1 like

Please or to participate in this conversation.