Fateh Alrabeai
Fateh Alrabeai

Reputation: 730

How to get the sum column values in laravel in model?

I was told that I can get the sum of certain column values using a function in model instead of doing this code with foreach :

$orders = Order::where('place_id',1)->select('delivery_fees')->get()->toArray();
        $orderArray = [];
        foreach ($orders as $order)
        {
            $orderArray[] = $order['delivery_fees'];
        }
$deliveryCostTotal = array_sum($orderArray);

How can I do that ?

Upvotes: 0

Views: 2044

Answers (4)

Gaurav Dhiman
Gaurav Dhiman

Reputation: 60

Try like this please

$deliveryFees = Order::where('place_id',1)->sum('delivery_fees');

Upvotes: 1

Kamlesh Paul
Kamlesh Paul

Reputation: 12391

You can use laravel sum function

$deliveryCostTotal = Order::where('place_id',1)->sum('delivery_fees');

https://laravel.com/docs/6.x/queries#aggregates

Upvotes: 3

Ahmed Ali
Ahmed Ali

Reputation: 1966

As your problem is solved but I am considering my answer as clearing your confusion in array_sum and adding data in array . because you are only setting value to array and overriding it, use array_push to add data in array.

 $orders = Order::where('place_id',1)->select('delivery_fees')->get()->toArray();
            $orderArray = [];
            foreach ($orders as $order)
            {
               array_push($orderArray,$order['delivery_fees']);
            }
    $deliveryCostTotal = array_sum($orderArray);

Upvotes: 0

TsaiKoga
TsaiKoga

Reputation: 13394

Using Mysql SUM

$deliveryCostTotal = Order::where('place_id',1)->selectRaw('SUM(delivery_fees) AS cost_total')->value('cost_total');

Upvotes: 2

Related Questions