Ahmed Guesmi
Ahmed Guesmi

Reputation: 370

I'm getting an empty var after I do a foreach in laravel

I get a empty result when really i should get 3500

 $transcationhist = Transcationhistorique::whereDate('created_at', Carbon::today())->pluck('amount');
    
 $amount = 0 ;

 foreach ($transcationhist as $p) {

    $amount = $amount + $p['amount'];

 }

Upvotes: 1

Views: 57

Answers (2)

MyLibary
MyLibary

Reputation: 1771

Pluck would return a flat array in your case, use it that way:

$transcationhist = Transcationhistorique::whereDate('created_at', Carbon::today())->pluck('amount');

 $amount = 0 ;

 foreach ($transcationhist as $p) {

    $amount += $p;

 }

Upvotes: 2

Davit Zeynalyan
Davit Zeynalyan

Reputation: 8618

If you want to sum amount, tat case use this code

$amount = Transcationhistorique::whereDate('created_at', Carbon::today())->sum('amount');

or you can use this

$transcationhist = Transcationhistorique::whereDate('created_at', Carbon::today())
    ->pluck('amount');
$amount = $transcationhist->sum();

And finally if you want to use foreach then use this code

$transcationhist = Transcationhistorique::whereDate('created_at', Carbon::today())
    ->get(['amount']);

 $amount = 0 ;

 foreach ($transcationhist as $p) {
    $amount = $amount + $p['amount']; // or $p->amount
 }

Upvotes: 4

Related Questions