April 22, 2018 —John Koster
The wrap
static method is similar to the make
static method, except that it will create a collection from any value supplied to it. This method is particularly helpful when writing methods or functions where the a collection instance is expected.
1public static function wrap(2 $value3);
In the following example, we will create a new instance of a User
class and wrap the User
instance inside a new collection:
1use Illuminate\Support\Collection;2 3$user = new User;4 5$users = Collection::wrap($user);
Since the wrap
method will not wrap a value if it is already a collection, it can be used to ensure that function or method arguments are always a collection:
1use Illuminate\Support\Collection;2 3function sendWelcomeEmails($users) {4 // Ensure that the users is always a collection.5 Collection::wrap($users)->each->sendWelcomeEmail();6}
We could invoke our example sendWelcomeEmails
function like so:
1// By supplying a single user instance.2$user = new User;3 4sendWelcomeEmails($user);5 6// By supplying a collection of users.7$users = Collection::wrap($user);8 9sendWelcomeEmails($users);
∎
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.