agyanadda@gmail.com

Laravel Collections

Database and Eloquent 1 min read Updated Dec 2, 2026 Topic 18 of 31

A Collection is a powerful wrapper around an array. Every Eloquent get() returns one, and you can create your own with collect([...]).

Most used methods

Method What it does
map(fn) change every item
filter(fn) keep items that pass a test
pluck('name') take one field from every item
sum('price'), avg(), max() totals and averages
sortBy('price'), sortByDesc() sort
groupBy('city') group into sub-collections
first(), last(), count() single items and counts
where('status', 'paid') filter by a field
unique(), take(5), chunk(3) trim and split
isEmpty(), contains() checks
toArray(), toJson() convert

Methods can be chained, and most return a new collection, leaving the original unchanged.

Collection or database?

Collection methods run in PHP memory. To filter thousands of rows, filter in the query (where()) instead of loading everything and using filter().

Example

Example — Order summary with collections PHP
<?php
$orders = collect([
    ['customer' => 'Asha', 'city' => 'Patna',  'amount' => 499, 'status' => 'paid'],
    ['customer' => 'Ravi', 'city' => 'Delhi',  'amount' => 999, 'status' => 'paid'],
    ['customer' => 'Neha', 'city' => 'Patna',  'amount' => 299, 'status' => 'failed'],
    ['customer' => 'Amit', 'city' => 'Patna',  'amount' => 799, 'status' => 'paid'],
]);

$paid = $orders->where('status', 'paid');

echo $paid->sum('amount');                          // 2297
echo $paid->pluck('customer')->implode(', ');        // Asha, Ravi, Amit
print_r($paid->groupBy('city')->map->count()->all()); // [Patna => 2, Delhi => 1]

where() keeps paid orders, sum() totals them, pluck() takes the names, and groupBy()->map->count() counts paid orders per city.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which method takes one field from every item?

Exercise 2 True / False

Eloquent's get() returns a Collection.

Exercise 3 Fill in the Blank

Create a collection from an array with the ___() helper.

Frequently Asked Questions

map() returns a new collection with the changed values. each() just loops over the items, for example to send emails, and returns the original collection.