Read this line from left to right: collect($menu)->filter(...)->pluck("name"). Take the menu, filter it, then take the names. You can guess what it does before knowing a single one of its methods. Code that reads like the order of the work is what this lesson is about.
A collection is an array wrapped in an object, with methods you can chain (call one after another): filter, transform, take one column, group, add up. Picture the kitchen of Mrs. Tini's Stall with a conveyor belt. Plates pass from station to station: the first station removes the dishes under $7, the second writes down their names, the last one adds up the total. Each station does one thing. In a collection, each station is one method, for example filter(), which filters, and the order reads from left to right. This lesson, the last one before Generators, also brings together two modern PHP features often used with collections: enums and match.
Without a collection: nested array functions
This is the menu data used throughout this lesson, with the same prices as in the Advanced Arrays lesson. The echo line takes the names of the dishes that cost at least 7:
<?php
$menu = [
["name" => "Fried Rice", "category" => "food", "price" => 15],
["name" => "Chicken Noodles", "category" => "food", "price" => 12],
["name" => "Iced Tea", "category" => "drink", "price" => 5],
["name" => "Crackers", "category" => "snack", "price" => 2],
["name" => "Orange Juice", "category" => "drink", "price" => 7],
];
echo json_encode(array_column(array_filter($menu, fn ($m) => $m["price"] >= 7), "name"));
// ["Fried Rice","Chicken Noodles","Orange Juice"]
The result is right, but you read that code from the inside out: array_filter first (the innermost), then array_column, then json_encode. With one more step, the brackets pile up even deeper.
The MiniCollection class: chained methods
Now wrap the array in a class (the OOP Basics lesson), and make filter() and pluck() return a new MiniCollection object:
class MiniCollection {
public function __construct(private array $items) {}
public function filter(callable $condition): MiniCollection {
return new MiniCollection(array_filter($this->items, $condition));
}
public function pluck(string $column): MiniCollection {
return new MiniCollection(array_column($this->items, $column));
}
public function sum(string $column): int {
return array_sum(array_column($this->items, $column));
}
public function all(): array {
return $this->items;
}
}
$result = (new MiniCollection($menu))
->filter(fn ($m) => $m["price"] >= 7)
->pluck("name")
->all();
echo json_encode($result); // ["Fried Rice","Chicken Noodles","Orange Juice"]
callable $conditionmeans the parameter$conditionholds a function, here the callbackfn ($m) => $m["price"] >= 7.- Because
filter()andpluck()return aMiniCollection, the next method can be attached right away with->. Attaching methods this way is called method chaining. - The order now reads from top to bottom, exactly the order of the work.
- Inside, it is still the same array functions. The class only makes the order easy to read.
Laravel Collections
Laravel already has a class like MiniCollection that is far more complete: Illuminate\Support\Collection. You make one with the collect() function. The output below comes from Laravel 13 on PHP 8.4:
echo collect($menu)->filter(fn ($m) => $m["price"] >= 7)->pluck("name");
// ["Fried Rice","Chicken Noodles","Orange Juice"]
echo collect($menu)->groupBy("category")->map(fn ($g) => $g->pluck("name"));
// {"food":["Fried Rice","Chicken Noodles"],"drink":["Iced Tea","Orange Juice"],"snack":["Crackers"]}
echo collect($menu)->sum("price"); // 41
echo collect([10, 20, 30])->sum(); // 60
echo collect([1, 2, 3, 4])->map(fn ($n) => $n * 2)->last(); // 8
collect($array)wraps an array in a collection.filter()filters with a callback,map()transforms every item,pluck("name")takes one column from every row.groupBy("category")groups the rows by that column.sum()adds up (sum("price")adds up one column),first()andlast()take the first and the last item.echoon a collection prints it as JSON, and->all()gives back a plain array.- Outside Laravel, install it with
composer require illuminate/collections.
In the last example, map() turns [1, 2, 3, 4] into [2, 4, 6, 8], then last() takes 8.
The keys come along
filter(), just like array_filter in the Advanced Arrays lesson, keeps the old keys. From [1, 2, 3, 4, 5], the items that pass the filter $n > 3 are 4 (key 3) and 5 (key 4). The keys are not renumbered from 0, so the JSON becomes an object (key and value pairs in { }), not a list in [ ]:
echo collect([1, 2, 3, 4, 5])->filter(fn ($n) => $n > 3); // {"3":4,"4":5}
echo collect([1, 2, 3, 4, 5])->filter(fn ($n) => $n > 3)->values(); // [4,5]
What you get is {"3":4,"4":5}, not [4,5]. values() (or array_values() for a plain array) renumbers from 0. Without it, ->get(0) (take the item with key 0) after a filter returns null, because key 0 is gone. pluck() and array_column() always renumber, which is why the menu names in the earlier example were already printed as a list in [ ].
Enum and match, used together
The category column may hold only three values. An enum (a closed list of values, from the Advanced OOP lesson) turns those three values into one type. match (from the Control Flow lesson) turns each value into a label:
enum Category: string {
case Food = "food";
case Drink = "drink";
case Snack = "snack";
public function isDeliverable(): bool {
return $this !== Category::Snack;
}
}
function categoryLabel(Category $k): string {
return match ($k) {
Category::Food => "Main dish",
default => "Side",
};
}
echo categoryLabel(Category::Food) . "\n"; // Main dish
echo categoryLabel(Category::from("drink")) . "\n"; // Side
var_export(Category::Snack->isDeliverable()); // false
enum Category: stringis a backed enum: everycasecarries a string value.Category::from("drink")turns text from the data into its case, hereCategory::Drink.- An enum may have methods. Inside such a method,
$thisis the case in use, for exampleCategory::Snackon the last line. matchchecks the cases one by one. A case that isn't named goes todefault, soDrinkandSnackboth become "Side".- A parameter of type
Categoryrefuses plain text:categoryLabel("food")throws aTypeError.
⚠️ Leftover keys and results nobody kept
- Forgetting that the keys come along. After
filter(),[0]or->get(0)may givenull, and the JSON turns into an object. Add->values(). - Thinking a method changes the original collection.
filter(),map()andpluck()return a new collection. Ifcollect($menu)->filter(...)is neither stored in a variable nor chained to another method, its result is simply lost. collect()outside Laravel. Without theilluminate/collectionspackage, PHP stops withCall to undefined function collect().matchwithoutdefault. A case that isn't named throwsUnhandledMatchError. Name every case, or close withdefault.
TL;DR: A collection is an array wrapped in an object, with methods you can chain (call one after another). Its steps read from top to bottom, unlike nested array functions (functions inside functions) that you read from the inside out. In Laravel, collect($array) makes one: filter() filters, map() transforms, pluck() takes one column, groupBy() groups, sum() adds up (collect([10, 20, 30])->sum() = 60), last() takes the last item, and echo prints it as JSON. filter() keeps the old keys (filtering [1, 2, 3, 4, 5] with $n > 3 gives {"3":4,"4":5}, not [4,5]), so add values() to renumber from 0. Modern PHP also has backed enums: a closed list of values where each case carries a value, for example enum Day: string { case Monday = "monday"; ... } in the exercise. An enum may have methods, and is often paired with a match that has a default for the cases it doesn't name.
⚡ A chain of methods, read from the top
Write:
$result = (new MiniCollection($menu))
->filter(fn ($m) => $m["price"] >= 7)
->pluck("name")
->all();
Meaning: MiniCollection is a class that wraps the array $menu (a list of dishes with a name and a price). filter() keeps the dishes that cost at least 7, pluck("name") takes their names, and all() gives back a plain array. filter() and pluck() return a new MiniCollection, so the next method is attached right away with ->. The order matches the order of the work, unlike nested array functions (functions inside functions), which you read from the inside out.
⚡ collect() in Laravel
Write:
echo collect($menu)->filter(fn ($m) => $m["price"] >= 7)->pluck("name");
echo collect([10, 20, 30])->sum(); // 60
Meaning: collect($array) wraps an array in a collection: an array inside an object, with methods you can chain. filter() filters, map() transforms every item, pluck() takes one column, sum() adds up, and echo prints it as JSON.
⚡ The keys come along
Guess first: does echo collect([1, 2, 3, 4, 5])->filter(fn ($n) => $n > 3); print [4,5]?
No, {"3":4,"4":5}. filter() keeps the old keys (3 and 4), so the JSON turns into an object. Add ->values() to get [4,5].
Meaning: filter(), map() and pluck() return a new collection, and the original collection does not change. A result that is neither stored in a variable nor chained to another method is lost.