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

shanely's avatar

I cannot sum in model

Hi, can I ask what is wrong with this.

Model Order.php

 public function getTotalPriceAttribute() {
        return $this->quantity' * $this->price;
    }

now in tinker I cannot do

$o = Order::find(1);
$o->sum('total_price');//it gives me error cannot find column
0 likes
30 replies
ctroms's avatar

It looks like you have an additional ' in your return after "quantity"

Try

public function getTotalPriceAttribute() {
        return $this->quantity * $this->price;
    }
shanely's avatar

@ctroms ,

sorry for the wrong typo, but I tried doesn't sum, in my view I also have this

@foreach($orders as $order)
    {{  $order->sum('total_price')  }} //Invalid column name 'total_price'
@endforeach 

zachleigh's avatar

Maybe getTotalPriceAttribute should be setTotalPriceAttribute.

zachleigh's avatar

That just creates the attribute. getTotalPriceAttribute gets the attribute total_price on your model, but allows you to modify it first. In your case, this attribute doesnt exist so you get an error. setTotalPriceAttribute creates the attribute. Then you should be able to do this:

$order->sum('total_price')
shanely's avatar

@zachleigh ,

I am confuse can you please guide me.

  public function getTotalPriceAttribute() {
        return $this->quantity * $this->price;
    }

 public function setTotalPriceAttribute() {
        // I don't know the code here
    }

zachleigh's avatar
public function getTotalPriceAttribute() {
        // you dont need this method
    }

 public function setTotalPriceAttribute() {
        return $this->quantity * $this->price;
    }
shanely's avatar

@zachleigh ,

            <td class="total-value"><div id="sumtotal">
                     @foreach($orders as $order)
                         {{number_format($order->sum('total_price'),2,'.',',')   }}   
                     @endforeach
                 </div></td>

it gives me this error

Invalid column name 'total_price'

d3xt3r's avatar

sum() is an aggregate function which will work if column is there in database. For computed property, above should work for you unless, there's something wrong with model itself. Show your model class ...

shanely's avatar

@d3xt3r ,

This is only I have

class Order extends Model
{
   
    public $primaryKey = 'pno';
    public $timestamps = false;
    protected $fillable = ['pno','quantity','unitprice'];

    public function getTotalPriceAttribute() {
       
    }
    public function setTotalPriceAttribute() {

        return $this->quantity * $this->unitprice;

    }

}


shanely's avatar

@zachleigh ,

I get error if I do this Invalid column total_price


  <td class="total-value"><div id="sumtotal">
                     @foreach($orders as $order)
                         {{number_format($order->sum('total_price'),2,'.',',')   }}   
                     @endforeach
                 </div></td>

d3xt3r's avatar

You don't even need an accessor, can be simple function like totalPrice() , but if you wish

@zachleigh Trouble visualising, why are you insisting on mutator than accessor.

class Order extends Model
{
   
    public $primaryKey = 'pno';
    public $timestamps = false;
    protected $fillable = ['pno','quantity','unitprice'];

    public function getTotalPriceAttribute() {
        return $this->quantity * $this->unitprice;
    }
}

// and access it like $order->total_price // sum will not work
1 like
zachleigh's avatar

And what about this?

{{ $order->total_price}} 

Just out of curiosity, why are you summing total_price on the order when each order contains only one total_price?

shanely's avatar

@zachleigh ,

Ok how do I get all the sum ? i have this data.like this

orderid           name                             quantity                  price              total                 
    7                 pen-blue                        3                               4.00                 12.00
    5                 board-red                      2                               4.00                8.00
        6                crayon                               1                               50.00                 50.00

what I want is to sum the total column. that is what I want to acheive, I thought the given solution is to sum the total

d3xt3r's avatar

sum based on what ??? all the columns in order table ????

Tell me first, forget about laravel, how would you sum that in sql ???

shanely's avatar

@d3xt3r ,

select sum( quantity * unitprice ) as overalltotal
from ordertable
d3xt3r's avatar

Probably you are unsure at this point of what you need, as i don't understand where the above would be applicable, But you will figure it out later ....

If its only the above query that you need then ...

total = DB::table('ordertable')->sum(DB::raw(' quantity * unitprice '));
1 like
Prullenbak's avatar
Level 26

The question is not that weird.

Normally, if you'd do

class Order extends Model
{
   
    public $primaryKey = 'pno';
    public $timestamps = false;
    protected $fillable = ['pno','quantity','unitprice'];

    public function getTotalPriceAttribute() {
        return $this->quantity * $this->unitprice;
    }
}

You should be able to get the new total_price attribute by doing $order->total_price. Does that work? It should.

Now if you want the sum of the total prices of a list of orders (which is clearly what you want), you can't use the new total_price accessor for that. But you can just loop through your orders and sum them up yourself?

shanely's avatar

Thank you guys, I apologize for having hard time to explain. Thank you.

ctroms's avatar

@shanely @Prullenbak As an alternative to summing in a for loop, you can call sum with your accessor if you first receive a collection. In your case, something like this should work.

$ordersTotal = Order::all()->sum('total_price');

As always, use whatever makes sense in your case.

ctroms's avatar

@Prullenbak In this case it might be. But there are perfectly valid reasons for doing it in a loop too.

d3xt3r's avatar

I don't understand, loop, no loop, and what is the sum() function on collection is doing behind the scene. array_reduce() ???

And on a side note ,

$ordersTotal = Order::all()->sum('total_price');

is highly inefficient way to deal with this, you don't load entire table in memory to calculate the sum, unless, its very complex calculation and beyond the scope of database.

ctroms's avatar

@d3xt3r Yes sum does call array_reduce behind the scenes. Yes in this case, it is not likely the best way to deal with this but it is the only way that I know of to call sum on a custom attribute. Per your suggestion, the raw db query would be better in this case. I was just trying to give additional options to answer the question by the OP and let them decide. To be honest, assuming that $orders represented all orders, I'm still unsure as to why sum was being called on a single record in the foreach loop.

d3xt3r's avatar

@ctroms Ya, its a messed up question, but glad that you agree on calculating the sum within the db call itself, if they are capable of, then why not utilise it :)

Please or to participate in this conversation.