Technical · Dispatch № 18

The Difference Between collect and wrap in Laravel Collections

Two ways to build a Collection — and why wrap is safer when the input might not be iterable.

Today, I learned that Laravel collections have a wrap method, which performs a similar function to the collect method. So, let me explain what the key differences are.

I.collect method

The collect() function creates an instance of a Collection from the value provided. If the input is already a collection, it simply returns the collection untouched.

$collection = collect([1, 2, 3]); // Returns Collection([1, 2, 3])
 
$existing = collect([4, 5, 6]);
$collection = collect($existing); // Returns original Collection([4, 5, 6])

II.wrap method

The Collection::wrap() method always guarantees a Collection output, regardless of the input type or existing structure. If the input is not an array or a Collection, it wraps it in an array before creating a Collection.

Collection::wrap('Alice'); // Returns Collection(['Alice'])
Collection::wrap(['Alice', 'Bob']); // Returns Collection(['Alice', 'Bob'])
Collection::wrap(collect(['Alice', 'Bob'])); // Returns Collection(['Alice', 'Bob'])

There is now a helper function for Collection::wrap. Should we have one?