wrap() and unwrap()

Brief Introduction About wrap()

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

Signature

wrap() method can be found in Illuminate\Support\Collection class. The structure of the 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 a parameter from the user and checks whether the value is an instance of the Collection class. If a condition is satisfied then it returns a collection instance of the provided parameter otherwise value is converted to a new collection instance.

To make wrap() more clear let’s look at its example:

use App\Product;
use Illuminate\Support\Collection;
$product = new Product();
$products = Collection::wrap($product);

At first, we created an instance of the Product model and then wrapped the 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 collected.

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;
}

Let’s 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 whether the argument supplied is an array.

Asmit Nepali, a Full Stack Developer, holds a Software Engineering degree from Gandaki College of Engineering and Science. Proficient in PHP Laravel, Vue.js, MySQL, Tailwind, Figma, and Git, he possesses a robust technical skill set.

Leave a Comment