Colin
Colin

Reputation: 735

Laravel Collection won't pull a value

I have a Laravel Collection that I am pushing a value to e.g. 'orange'. When I test for a value and attempt to pull a value, the collection remains the same.

$collection = collect(['red', 'green', 'blue']);

$collection->push('orange');
    
if($collection->contains('green')) {

    logger('Got green!');
        
    $collection->pull('green');
 }

I'm sure I am missing something trial but why is green not removed from the final collection?

Upvotes: 3

Views: 1086

Answers (2)

Mohamed Ahmed
Mohamed Ahmed

Reputation: 830

because pull method remove item by its key not value ,so you need to get the item key ( index ) first so that you can pass it to pull or forget method to remove it .

you can do like this :-

$collection = collect(['red', 'green', 'blue']);

$collection->push('orange');
    
if($collection->contains('green')) {

    logger('Got green!');
          $index = $collection->search('green');

    $collection->pull($index);
    // $collection->forget($index);

 }

Upvotes: 3

PythonicSpeaker
PythonicSpeaker

Reputation: 421

Well, actually simple non-associative array in php still associative, but its keys are indexes and you can imagine your array as

[0 => 'red', 1 => 'green', 2 => 'blue', 3 => 'orange']

Pull method pulls the item from array by its key. So if you expect to orange item being pulled you should call the method with that item's index:

$collection>pull(3);

Upvotes: 0

Related Questions