Laravel 5 Collections: Creating a Copy of a Collection With toBase

April 22, 2018 —John Koster

The toBase method will return a new collection instance containing all of the data in the current collection instance. This can be useful for method chaining when you need to modify the collection's contents without changing the original collection instance.

#Signature

1public function toBase();

#Example Use

The following examples demonstrate the usage of the toBase method. We will create a collection of names and then clone it using the toBase method and then modify the resulting collection.

1 
2// Create a collection of names.
3$names = collect([
4 'Alice',
5 'Bob',
6 'Charlie',
7]);
8 
9// Create an uppercase-variant collection of names.
10$upperCaseNames = $names->toBase()->map(function ($name) {
11 return mb_strtoupper($name);
12});

After the above code has executed, the local variables would contain the following elements:

The $names Collection Elements:

Index Value
0 Alice
1 Bob
2 Charlie

The $upperCaseNames Collection Elements:

Index Value
0 ALICE
1 BOB
2 CHARLIE

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.