<?php
use Illuminate\Support\Collection;
// Create collection
$posts = collect(Post::all());
// Transform data
$published = $posts
->filter(fn ($post) => $post->is_published)
->map(fn ($post) => [
'title' => $post->title,
'author' => $post->author->name,
'url' => route('posts.show', $post),
])
->values(); // Reset keys
// Group by author
$byAuthor = $posts->groupBy('author.name');
// Get unique tags
$tags = $posts
->pluck('tags')
->flatten()
->unique()
->sort()
->values();
// Partition into two collections
[$published, $drafts] = $posts->partition(
fn ($post) => $post->is_published
);
// Complex aggregation
$stats = $posts
->groupBy('category')
->map(fn ($group) => [
'count' => $group->count(),
'avg_views' => $group->avg('views'),
'total_comments' => $group->sum('comments_count'),
]);
// Higher-order messages
$totalPosts = $users->sum->posts->count();
$names = $users->map->name;
$published = $posts->filter->is_published;
// Chunk processing
$posts->chunk(100)->each(function ($chunk) {
// Process 100 posts at a time
$chunk->each->update(['processed' => true]);
});
<?php
use Illuminate\Support\Collection;
// Extend Collection with custom methods
Collection::macro('toSelectArray', function () {
return $this->mapWithKeys(function ($item) {
return [$item->id => $item->name];
})->toArray();
});
// Usage
$options = User::all()->toSelectArray();
// ['1' => 'John', '2' => 'Jane', ...]
// Pipe through custom transformation
$result = $posts->pipe(function ($collection) {
return $collection
->filter->is_featured
->take(5)
->values();
});
Laravel collections provide a fluent, powerful API for working with arrays. Every Eloquent query returns a collection, but I also create collections from arrays with collect(). Methods like map(), filter(), reduce(), groupBy(), and sortBy() transform data without loops. Collections are lazy—operations don't execute until you call terminal methods like toArray() or values(). The pipe() method passes collections through custom transformations. Higher-order messages simplify common operations—$users->sum->posts->count() sums post counts across users. Collections make complex data transformations readable and chainable. I prefer collections over manual array manipulation for cleaner, more expressive code.