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

aureliee123's avatar

sum in collection takes to long

i building a laravel nova admin panel and using custom metrics to do some calculations however it's taking a loooot of time ( 10 minutes ) i doon't understand why i used : $model->get()->sum('attribute') and foreach

nothing has changed

any suggestion is welcomed

0 likes
9 replies
Snapey's avatar

try using sum before the get, otherwise you are loading every model into memory

Install Laravel debugbar so that you can see what is happening

1 like
aureliee123's avatar

is it possible to sum a custom function before the get ?

1 like
laracoft's avatar

@aureliee123

  1. If you sum() after get(), that is using Laravel's collection, i.e. retrieve all records from MySQL and summing in PHP
  2. If you sum() without get(), this would be using Laravel's eloquent, i.e. summing in MySQL, which is way more efficient
1 like
aureliee123's avatar

@sinnbeck @laracoft thank you guys but i'm trying to sum a function here's an example ;

i have orders model and a function named total() it calcualtes the order total ( based on delivery fees and products and other params )

so for a list of orders i have to sum all the totals

i tried setTotalAttribute but it didn't work and using collections the result is too slooow

Snapey's avatar

@aureliee123 You should save the total against each order rather than recalculating it every time. You can then ask the database to sum the order total. If your total() function is pulling records from other tables, it might work fine when reviewing one order, but when totalling multiple orders you will have a horrible n+1 issue.

laracoft's avatar

@aureliee123

In such a scenario, your total() should run at the point of placing the order or when the delivery is confirmed, then the calculated amount is saved into the order like what Snapey suggested.

So you will need to create a total field in your orders table and it should start as NULL by default, this way, you won't need the setTotalAttribute(...).

Attributes should not contain queries, it will likely make the app very slow over time, I only use attributes to reformat data or do simple maths on fields that are already loaded.

Attributes also can't be utilized by MySQL. These are all design considerations the architect will have to factor in.

1 like
aureliee123's avatar

i did what you suggested and i'm using nova metrics to display the result in the dashboard but it is still very slow

Please or to participate in this conversation.