Laravel Collections – wrap() and unwrap() Methods

laravel collections wrap and unwrap methods

This post is part of the series Laravel Collection

Other posts in this series:

  1. Laravel Collections – Introduction to Collections
  2. Laravel Collections – make Method
  3. Laravel Collections – wrap() and unwrap() Methods (Current)

In this post, we will look at how wrap() and unwrap() methods can be used when dealing with Laravel Collections. This is a third part of Laravel Collections Series.

Laravel Collection wrap() Method

As I discussed in previous post that the make() method create a new instance of a collection from an array. wrap() method is similar to make() method, except it will create a collection from any value supplied to it.

This function is very helpful where you have to make sure only the collection instance is expected.

Signature

Below is the signature of wrap() method defined in Illuminate\Support\Collection class.

As you can see in the above signature, Laravel is checking if the value provided is an instance of Collection class, if it then returns a collection instance of the value, if not then convert the value to a new collection instance.

Laravel Collection wrap() Method Example

For practical use, let’s go through with an example.

Above, we have created a new instance of Product model which will return the collection and then wrapped the product inside a new collection called products.

As wrap method will not wrap a value if the value is a collection, it can be used to make sure that function or method arguments are always a collection.

We can use the above function like below:

Laravel Collection unwrap() Method

The unwrap() method is the opposite of wrap() method, if the provided value is already a collection, the collection’s underlying items will be returned. If not then the value will be returned as it is without modification.

Signature

Below is the signature of unwrap() method defined in Illuminate\Support\Collection class.

Laravel Collection unwrap() Method Example

As we checked in the wrap() method that the function or method arguments are always a collection, in unwrap() we can check that argument supplied to function is always an array.

That’s it for now. If you have any question please leave it in the comments box below.

Continue reading this series: