The when should be seperate
$users = User::where('name', 'like', "%$search%")
->when($is_adult, function ($query) {
$query->where('age', '>', 18);
})
->paginate(15)
->withQueryString();
And shouldn't 18 be included? >=
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have a table with search box and a checkbox button for adult users (age above 18). The users have a name and an email. The issue is when the adult checkbox is checked and you search by an email, it doesn't return any result.
For example the following two rows in the database:
Name Age Email
Concepcion Turcotte 16 [email protected]
Emmy Hoeger 67 [email protected]
and I Search for "kozey." it returns the two rows above. But if I check the adult checkbox and search for "kozey.", I get no results. This is the query:
$is_adult = $request->input('adult');
$search = $request->input('search');
$users = User::when($is_adult, function ($query, $search) {
$query->where('name', 'like', "%$search%")->orWhere('email', 'like', "%$search%")->where('age', '>', 18);
})->paginate(15)->withQueryString();
Please or to participate in this conversation.