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

Laracast13's avatar

laravel merge multiple query

Hello Need merge multiple query, if it possible. Using 4 query. After search $seach gives product (using foreach in blade) and with a b c showing total prices for all products (in blade using {{$a}} {{$b}} {{$c}})

$seach = Product::where('cat', 'like', "%{$n}%")->latest()->paginate(50);
$a = Product::where('cat', 'like', "%{$n}%")->selectRaw('SUM(price_a) as total')->value('total');
$b = Product::where('cat', 'like', "%{$n}%")->selectRaw('SUM(price_b) as total')->value('total');
$c = Product::where('cat', 'like', "%{$n}%")->selectRaw('SUM(price_c) as total')->value('total');

It is possible make it as one query. Or maybe only for a b c .

0 likes
3 replies
tykus's avatar

You are paginating the first query - so any aggregations (SUM) will be limited by the page size. At best, you could make two queries - the paginated records and the aggregations.

Laracast13's avatar

@tykus

For this can make one query?

$a = Product::where('cat', 'like', "%{$n}%")->selectRaw('SUM(price_a) as total')->value('total');
$b = Product::where('cat', 'like', "%{$n}%")->selectRaw('SUM(price_b) as total')->value('total');
$c = Product::where('cat', 'like', "%{$n}%")->selectRaw('SUM(price_c) as total')->value('total');
sr57's avatar

@www888

st like this

Product::where('cat', 'like', "%{$n}%")->selectRaw('SUM(price_a) as ta,SUM(price_b) as tb,SUM(price_c) as tc')->get(['ta','tb','tc'])->toArray();

Please or to participate in this conversation.