Script Lover
Script Lover

Reputation: 381

Why each() does not working with pluck() using laravel?

In my token table I have two records but I need only amount column.

$hasToken = $this->hasMany(Token::class, 'user_id', 'id')->pluck('amount')->toArray();

Above relation returns two record

array( "0" => 500, "1" => 500, )

I want to plus them by using laravel each() or every() function but does not working

$hasToken->each(function ($item, $key) use($totalTokens) {
    $totalTokens += $item;
});

Also I can't try to check count in if-statement using below script

if($hasToken->count() > 0){ ... }

because it is returning error.

Upvotes: 0

Views: 81

Answers (1)

Mozammil
Mozammil

Reputation: 8750

There are couple of things wrong here.

First, you should not convert your collection to an Array if you want to perform an each() over it. That's a method specific to Laravel Collections.

$hasToken = $this->hasMany(Token::class, 'user_id', 'id')->pluck('amount');

Second, you want to modify a value totalTokens which I assume is outside your scope.

So, you should pass it by reference. The following should work.

$totalTokens = 2; 

$hasToken->each(function ($item, $key) use(&$totalTokens) {
    $totalTokens += $item;
});

dd($totalTokens); // outputs 1002

Also $hasToken->count() should work again.

Edit: The & operator denotes that this variable is being passed by referenced to the closure.

If you omit the &, it means $totalTokens is passed by value to the closure. In other terms, it is copied to the closure. Any operations that you will do to the $totalTokens will not be known outside its scope.

Upvotes: 2

Related Questions