Laravel 5 Collections Static API: Ensure a Value Is a Collection With wrap

Laravel 5 Collections Static API: Ensure a Value Is a Collection With wrap

Laravel 5

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

public static function wrap(
    $value
);

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:

use Illuminate\Support\Collection;

$user = new User;

$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:

use Illuminate\Support\Collection;

function sendWelcomeEmails($users) {
    // Ensure that the users is always a collection.
    Collection::wrap($users)->each->sendWelcomeEmail();
}

We could invoke our example sendWelcomeEmails function like so:

// By supplying a single user instance.
$user = new User;

sendWelcomeEmails($user);

// By supplying a collection of users.
$users = Collection::wrap($user);

sendWelcomeEmails($users);

Start the Discussion

Leave a comment

Subscribe to our newsletter