wrap() and unwrap()

Brief introduction about wrap()

wrap() method creates new instance of collection from any value supplied to it. It is very much similar to make() method. If you want to make sure only collection instance is expected then this method is exactly that you need.

Signature:

wrap() method can be found in Illuminate\Support\Collection class. The structure of wrap method looks like this:

/**
 * Wrap the given value in a collection if applicable.
 *
 * @param  mixed  $value
 * @return static
 */
public static function wrap($value)
{
    return $value instanceof self
        ? new static($value)
        : new static(Arr::wrap($value));
}

wrap takes in parameter from the user and checks whether the value is instance of Collection class. If condition is satisfied then it returns collection instance of the provided parameter otherwise value is converted to new collection instance.

To make wrap() more clear lets look at its example:

use App\Product;
use Illuminate\Support\Collection;

$product = new Product();
$products = Collection::wrap($product);

At first, we created instance of Product model then wrapped product inside a new collection i.e. $products.

This method does not work for value which is not a collection. For that we can create a method that ensures the value is collection.

use Illuminate\Support\Collection;

function addProductsToOrder($products) {
    // Ensure that the products is always a collection.
    Collection::wrap($products)->each->addToOrder();
}

The above method can be used like:

// By supplying a single product instance
$product = new Product();
addProductsToOrder($product);

// By supplying a collection of products
$products = Collection::wrap($product);
addProductsToOrder($products);

Brief introduction about unwrap()

unwrap() is exact opposite of wrap() method. If a collection is provided to unwrap(), it returns items inside the collection. If not then the value is returned without modification.

Signature:

Here is how unwrap() is defined inside Illuminate\Support\Collection class.

/**
 * Get the underlying items from the given collection if applicable.
 *
 * @param  array|static  $value
 * @return array
 */
public static function unwrap($value)
{
    return $value instanceof self ? $value->all() : $value;
}

Lets see an example to know how unwrap() works:

use Illuminate\Support\Collection;

// Create a new collection of users
$users = collect([
    'Steve', 'Jared', 'Paul', 'James'
]);

// Get the collection items
$items = Collection::unwrap($users);

dd($items);
// [
  0 => "Steve"
  1 => "Jared"
  2 => "Paul"
  3 => "James"
]

In unwrap(), we can check if the argument supplied is array or not.

Leave a Comment