illuminate/collections
Illuminate Collections provides a fluent, chainable API for working with arrays and iterables in PHP. Includes Collection and LazyCollection with powerful mapping, filtering, grouping, sorting, and higher-order operations, used widely across Laravel and standalone projects.
Start by installing the package via Composer:
composer require illuminate/collections
This package provides the foundational Collection class used throughout Laravel ecosystems—often consumed indirectly via Laravel’s helpers like collect(). To use it directly, import the class:
use Illuminate\Support\Collection;
$collection = new Collection([1, 2, 3]);
The most immediate use case is transforming and querying arrays via fluent, chainable methods (e.g., map, filter, reduce, pluck). If you're already using Laravel, this package is already included—no need to install separately.
collect() helper for convenience:
$users = collect($rawUserArray)
->filter(fn($u) => $u['active'])
->map(fn($u) => $u['name'])
->values();
LazyCollection::make()) for memory-efficient processing of large data sets (e.g., iterating DB results without loading all records into memory).Collection instances; chain methods directly on results:
$activeUsers = User::where('active', true)->get()
->sortByDesc('created_at')
->take(10);
Collection at runtime using Collection::macro(), e.g., for domain-specific logic:
Collection::macro('snakeCaseKeys', function () {
return $this->mapWithKeys(fn($item, $key) => [Str::snake($key) => $item]);
});
->filter()->map()->values() over splitting into multiple statements).Collection is immutable for most methods—chains return new instances (e.g., filter() returns a new collection, original remains unchanged). This avoids side effects but may impact performance if used naively in tight loops.Collection implements ArrayAccess, prefer explicit methods like get(), first(), last() over array indexing ($collection[0]) for safety and readability.strictRules in your config or use PHPDoc for explicit type hints. Consider using @return Collection<int, string> in docblocks for clarity.LazyCollection is powerful but won’t help if you force eager evaluation (e.g., toArray(), all()). Only use lazy when you don’t need all results at once.when() and tap() are debugging staples:
$collection->tap(fn($c) => dump($c->count()))
->when($shouldFilter, fn($c) => $c->filter(...))
AppServiceProvider) only work if the provider is booted—remember to register them early.How can I help you explore Laravel packages today?