By 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.
#Signature
1public static function wrap(
2 $value
3);
#Example Use
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);
∎