Laravel 5 Collections Static API: Returning the Items of a Collection With unwrap

Laravel 5 Collections Static API: Returning the Items of a Collection With unwrap

Laravel 5

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

public static function unwrap(
    $value
);

Example Use

The following example demonstrates using the unwrap method to gain access to a collections underlying items:

use Illuminate\Support\Collection;

// Create a new collection.
$collection = collect([
   'Alice', 'Bob', 'Charlie' 
]);

// Get the collection's items.
$items = Collection::unwrap($collection);

We could use the unwrap method to help ensure that an argument supplied to a function is always an array:

use Illuminate\Support\Arr;
use Illuminate\Support\Collection;

function someArrayOnlyFunction($value) {
    // First, unwrap the value if it is a collection.
    $value = Collection::unwrap($value);

    // Next, let's ensure that the remaining value is an array.
    $value = Arr::wrap($value);

    // Now, we are guaranteed that the $value is an array.

}

Start the Discussion

Leave a comment

Subscribe to our newsletter