Why not use Eloquent sum()
$totalInstallations = $data->sum('numinst');
OR
$totalInstallations = $data->get()->sum('numinst');
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi, I've a query executed as follows:
$data = Application::select(['id','numinst','nomapp','idapp','fabricante','version','carpeta','comentarios']);
$numTotal = $numRecords = $data->count();
And then I have to get all the results to peform the next operation:
/*
* Heres is some code that adds optinonally where clause to the query
*/
if(!empty($searchPhrase)) {
// Search by a word or part of a phrase (center or user agent)
if(preg_match("/^[a-z\s]{3,}$/i", $searchPhrase)) {
$data->where(function($query) use ($searchPhrase) {
$query->orWhere('fabricante', 'like', '%' . $searchPhrase . '%');
// ->orWhere('osname', 'like', '%' . $searchPhrase . '%');
});
$numRecords = $data->count();
//dd($numRecords);
}
}
$totalInstallations = 0;
foreach($data->get() as $row) { // TODO: This row takes a lot of memory, #error message: Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes)
$totalInstallations += $row->numinst;
}
The poblem is that the query takes more thatn 128M, due this table contains around 0.5 M rows, and I need to perform the sum of the numinst field, and this is too much memory for my server and very dangerous
I'd like ti know if there's any way to perform the query in laravel as streaming, I mean using the fetch() PDO method, not the equivalent to fetchAll() that uses too much memory.
Thanks
Dani
Why not use Eloquent sum()
$totalInstallations = $data->sum('numinst');
OR
$totalInstallations = $data->get()->sum('numinst');
Please or to participate in this conversation.