Master Laravel Collections: Powerful Methods to Filter, Transform, and Analyze Data
This tutorial explains how Laravel Eloquent returns collections, how to create collections with the collect helper, and demonstrates essential collection methods such as filter, search, chunk, zip, map, each, tap, pipe, contains, whereNotIn, max, pluck, and avg, complete with code examples and expected outputs.
Laravel Eloquent returns a Collection object that provides a rich set of chainable methods for filtering, modifying, and aggregating data without additional database queries. The same methods can be used on plain arrays by converting them with the collect() helper.
Creating a Collection
You can retrieve a collection from the database:
$posts = App\Post::where('category', 'php')->get();Or create one manually:
$collection = collect([
[
'user_id' => '1',
'title' => 'Helpers in Laravel',
'content' => 'Create custom helpers in Laravel',
'category'=> 'php',
],
[
'user_id' => '2',
'title' => 'Testing in Laravel',
'content' => 'Testing File Uploads in Laravel',
'category'=> 'php',
],
[
'user_id' => '3',
'title' => 'Telegram Bot',
'content' => 'Crypto Telegram Bot in Laravel',
'category'=> 'php',
],
]);All subsequent operations work on this $collection instance.
filter()
The filter method keeps items that satisfy a callback and returns a new collection.
$filter = $collection->filter(function ($value, $key) {
return $value['user_id'] == 2;
});
$filter->all(); // returns only the item with user_id 2search()
searchreturns the key of the first matching value, or false if none is found. It uses loose comparison by default; pass true as the second argument for strict comparison.
$names = collect(['Alex', 'John', 'Jason', 'Martyn', 'Hanlin']);
$names->search('Jason'); // returns 2
$names->search(function ($value) {
return strlen($value) == 6;
}); // returns 3 (index of 'Jason')chunk()
chunksplits a collection into smaller collections of a given size.
$prices = collect([18, 23, 65, 36, 97, 43, 81]);
$prices = $prices->chunk(3);
$prices->toArray(); // [[18,23,65],[36,97,43],[81]]zip()
zipmerges the values of the collection with the values of the given array based on matching indexes.
$zipped = $collection->zip([1, 2, 3]);
$zipped->all(); // each original item is paired with the corresponding numbermap()
mapiterates over the collection, allowing you to modify each item and return a new collection.
$changed = $collection->map(function ($value, $key) {
$value['user_id'] += 1;
return $value;
});
$changed->all(); // user_id values become 2,3,4each()
eachruns a callback for every item. Returning false stops the iteration.
$collection->each(function ($item, $key) {
info($item['user_id']);
if ($key == 1) {
return false; // stop after the second item
}
});tap()
tappasses the collection to a callback without altering the original collection, useful for debugging or side‑effects.
$result = $collection->whereNotIn('user_id', [1,2])
->tap(function ($col) {
$col = $col->where('user_id', 1);
info($col->values());
})
->all();pipe()
pipealso passes the collection to a callback but returns the callback’s result.
$minId = $collection->pipe(function ($col) {
return $col->min('user_id');
});contains()
containschecks if a value (or a key/value pair) exists in the collection.
$contains = collect(['country' => 'USA', 'state' => 'NY']);
$contains->contains('USA'); // true
$contains->contains('UK'); // false
$collection->contains('user_id', '1'); // truewhereNotIn()
whereNotInfilters out items whose column value is in the given array.
$filtered = $collection->whereNotIn('user_id', [1,2]); // returns only the item with user_id 3max()
maxreturns the maximum value for a given key.
$maxId = $collection->max('user_id'); // 3pluck()
pluckextracts the values of a single column (or column/value pairs) from the collection.
$titles = $collection->pluck('title')->all(); // ['Helpers in Laravel','Testing in Laravel','Telegram Bot']
$pair = $collection->pluck('user_id','title')->all(); // ['Helpers in Laravel'=>1, ...]avg()
avg(or average) calculates the arithmetic mean of a numeric column.
$avg = collect([12,32,54,92,37])->avg(); // 45.4
$avgShoes = collect([
['shoes'=>10],['shoes'=>35],['shoes'=>7],['shoes'=>68]
])->avg('shoes'); // 30All of these methods operate on the collection in memory, meaning the database is queried only once (when the collection is first retrieved). Subsequent manipulations are performed using PHP’s array functions enhanced with Laravel’s fluent API.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
