SUM(value) as value SQL Query not working

  html, laravel, php, sql

so i have this functionin a clientPurchases class that selects the summation of value of a certain client on a certain month and year and returns it, if its empty returns 0.

my error is that the variable ‘total’ that display the total is returning with the wrong value

public function purchasesCount($month_id, $year_id)
    {    
        $purchasesCount = ClientPurchases::select(DB::raw('SUM(value) AS value'))
        ->where('client_id', $this->id)
        ->whereYear('date', '=', $year_id)
        ->whereMonth('date', '=', $month_id)
        ->get();

        if(!empty($purchasesCount->value)){
            return $purchasesCount->value;
        }else{
            return 0;
        }
    }

And then in my show.blade im trying to do a foreach to sum all the clients in a card whith this

<div class="col-md-4">
                <div class="carde card-1">
                    <h3>Clientes</h3>
                    <?php 
                        $total = 0;
                        foreach($clients as $client){
                           $valor = $client->purchasesCount($month, $year);
                           $total += $valor; 
                        }
                    ?>
                       
                    <h4 class="valor">{{ $total }} €</h4>
                    <h4 class="mes">{{date('F', mktime(0, 0, 0, $month - 1, 10))}}</h4>
                    <br>
                </div>
                </div>

im new to laravel so help would be grat tkx 🙂

Source: Laravel

Leave a Reply