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.
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.
php
$collection = collect([1, 2, 3]); // Returns Collection([1, 2, 3])
$existing = collect([4, 5, 6]);
$collection = collect($existing); // Returns original Collection([4, 5, 6])
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.
php
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?