By John Koster
The unwrap
method is the logical opposite of the wrap
method, in that if the provided value is already a collection, the collection's underlying items will be returned. If the provided value is not a collection instance, the value is simply returned without modification.
#Signature
1public static function unwrap(
2 $value
3);
#Example Use
The following example demonstrates using the unwrap
method to gain access to a collections underlying items:
1use Illuminate\Support\Collection;
2
3// Create a new collection.
4$collection = collect([
5 'Alice', 'Bob', 'Charlie'
6]);
7
8// Get the collection's items.
9$items = Collection::unwrap($collection);
We could use the unwrap
method to help ensure that an argument supplied to a function is always an array:
1use Illuminate\Support\Arr;
2use Illuminate\Support\Collection;
3
4function someArrayOnlyFunction($value) {
5 // First, unwrap the value if it is a collection.
6 $value = Collection::unwrap($value);
7
8 // Next, let's ensure that the remaining value is an array.
9 $value = Arr::wrap($value);
10
11 // Now, we are guaranteed that the $value is an array.
12
13}
∎