To convert an array to a collection in Laravel, you can use the collect
helper function. This function will create a new Illuminate\Support\Collection
instance from the given array.
Here’s an example:
$array = [1, 2, 3, 4];
$collection = collect($array);
// $collection is now a collection object containing [1, 2, 3, 4]
You can also pass a multidimensional array to the collect
function, and it will recursively convert the nested arrays to collections as well:
$array = [[1, 2], [3, 4], [5, 6]];
$collection = collect($array);
// $collection is now a collection object containing [[1, 2], [3, 4], [5, 6]]
The collect
function is a convenient way to create a collection from an array, especially if you need to work with the array items using the methods of the Illuminate\Support\Collection
class.
If you have an object that implements the Traversable
interface, you can also pass it to the collect
function and it will be converted to a collection.
$object = new ArrayObject([1, 2, 3, 4]);
$collection = collect($object);
// $collection is now a collection object containing [1, 2, 3, 4]