To create a collection from an array in Laravel's Illuminate/Collection package, you can make use of the collect()
helper function.
Here's an example of how you can create a collection from an array:
use Illuminate\Support\Collection;
$array = [1, 2, 3, 4, 5];
$collection = collect($array);
// You can also directly instantiate the Collection class:
$collection = new Collection($array);
You can then use various methods provided by the Collection class to manipulate and work with the data. For example:
// Filter the collection to only include even numbers
$filtered = $collection->filter(fn($value) => $value % 2 === 0);
// Map each value in the collection to its square
$mapped = $collection->map(fn($value) => $value * $value);
// Get the sum of all the values in the collection
$sum = $collection->sum();
// ... and many more!
By creating a collection from an array, you gain access to a wide range of helpful methods for working with the data in an elegant and efficient way.