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

aurorame's avatar

How to make query correctly?

I need to make selection from Users table with many condition i receive from API. I can receive data like:

money_less
money_adv
level_less
level_adv

etc..

If i receive money_less and money_adv i make request like this:

User::
	->when($request->input('money_less'), function ($query) {
		$query->where('money', '>', request()->input('money_less'));
	})
	->when($request->input('money_adv'), function ($query) {
		$query->where('money', '<', request()->input('money_adv'));
	})
	->get();
  1. How i can correctly do this request cause i need (can) to receive more than 20 condition and this construction seems terribly?
  2. How i can use request data inside function? If i share it function ($query, $request) i can't use input() function or receive data correctly
0 likes
3 replies
vincent15000's avatar

I do the same as you.

I just write my code a little differently.

$money_less = $request->money_less ?? null;
$money_adv = $request->money_adv ?? null;
...
User::
	->when($money_less, function ($query) use ($money_less) {
		$query->where('money', '>', $money_less);
	})
	->when($money_adv, function ($query) use ($money_adv) {
		$query->where('money', '>', $money_adv);
	})
	->get();
1 like
MichalOravec's avatar
User::when($request->money_less, function ($query, $moneyLess) {
		$query->where('money', '>', $moneyLess);
	})
	->when($request->money_adv, function ($query, $moneyAdv) {
		$query->where('money', '<', $moneyAdv);
	})
	->get();

or

User::query()
    ->when($request->money_less, fn ($query, $moneyLess) => $query->where('money', '>', $moneyLess))
    ->when($request->money_adv, fn ($query, $moneyAdv) => $query->where('money', '<', $moneyAdv))
    ->get();
2 likes
psrz's avatar

Maybe you can take a look at https://spatie.be/docs/laravel-query-builder/v5/introduction if it suits your needs.

That's a fantastic package to deal exactly with that situation. It will impose certain way of passing the filter parameters from the client (which is actually a good thing) but if you get the hang of it, you don't want to go back

2 likes

Please or to participate in this conversation.