Published in Laravel 5

Laravel 5 Collections: Retrieving and Removing an Element From a Collection With pull

By John Koster

The pull method will remove an item from the collection whilst returning its value. If the item is not in the collection, the optional $default value will be returned. The pull method will modify the original collection.

#Signature

1public function pull(
2 $key,
3 $default = null
4);

#Example Use

The following example demonstrates the basic use of the pull method:

1use Illuminate\Support\Collection;
2
3// Create a new collection instance.
4$collection = new Collection([
5 'first' => 'I am first',
6 'second' => 'I am second',
7 'third' => 'I am third'
8]);
9
10// Pull the third value from the collection.
11$value = $collection->pull('third');
12
13// null
14$doesNotExist = $collection->pull('non-existent');
15
16// default-value
17$alsoDoesNotExist = $collection->pull(
18 'non-existent',
19 'default-value'
20 );

After the above code has executed, the $value variable would contain the value I am third and the $collection variable would contain a value similar to the following output:

1object(Illuminate\Support\Collection)
2 protected 'items' =>
3 array
4 'first' => string 'I am first'
5 'second' => string 'I am second'