Laravel 5 Collections: Removing Collection Elements With forget

April 22, 2018 —John Koster

The forget method removes an item from the collection based on given $key. The forget method returns a reference to the original collection, meaning it modifies the collection instance it was called on.

#Signature

1public function forget(
2 $keys
3);

#Example Use

The following code example demonstrates how the forget method can be used to remove an item from a collection:

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]);
8 
9// Remove the 'first' item from the collection.
10$collection->forget('first');

The $collection will now contain only the second item, and will have a structure similar to the following:

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

Numerical keys can also be passed to the forget method to remove items from a collection:

1use Illuminate\Support\Collection;
2 
3// Create a new collection.
4$collection = new Collection([
5 'I am first',
6 'I am second'
7]);
8 
9// Remove the 'first' item from the collection
10// using a numerical key.
11$collection->forget(0);

Like before, the $collection will have a structure similar to the following output:

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

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.