Could we help you? Please click the banners. We are young and desperately need the money
Laravel Collections are one of the most powerful features in the framework. They allow developers to work with arrays and data sets in a clean, expressive, and chainable way. If you already know the basics of Laravel, mastering Collections will help you write shorter, more readable, and more efficient code.
Collections in Laravel are wrapper classes around arrays that provide dozens of helper methods. Instead of writing complex loops, you can use methods like "map", "filter", and "pluck" to transform and process data with ease.
$numbers = collect([1, 2, 3, 4, 5]);
// You can still use it like an array
echo $numbers[0]; // 1
Transforms each item in a collection. Perfect for formatting or modifying values.
$users = collect([
['name' => 'Alice', 'role' => 'user'],
['name' => 'Bob', 'role' => 'admin']
]);
$names = $users->map(function ($user) {
return strtoupper($user['name']);
});
print_r($names->all());
// Output: ['ALICE', 'BOB']
Removes items that don’t pass a given condition. Similar to "array_filter" in PHP, but more elegant.
$numbers = collect([10, 20, 30, 40, 50]);
$filtered = $numbers->filter(function ($number) {
return $number > 25;
});
print_r($filtered->all());
// Output: [30, 40, 50]
Extracts values from an array or object. Very handy when working with Eloquent results.
$users = collect([
['id' => 1, 'name' => 'Alice'],
['id' => 2, 'name' => 'Bob']
]);
$names = $users->pluck('name');
print_r($names->all());
// Output: ['Alice', 'Bob']
Reduces a collection to a single value, such as a sum or concatenation.
$numbers = collect([1, 2, 3, 4, 5]);
$sum = $numbers->reduce(function ($carry, $item) {
return $carry + $item;
}, 0);
echo $sum; // 15
Collections become even more powerful when you chain methods together:
$users = collect([
['name' => 'Alice', 'active' => true],
['name' => 'Bob', 'active' => false],
['name' => 'Charlie', 'active' => true],
]);
$activeNames = $users
->filter(fn($user) => $user['active'])
->pluck('name')
->map(fn($name) => strtoupper($name));
print_r($activeNames->all());
// Output: ['ALICE', 'CHARLIE']
Laravel Collections can make your code shorter, cleaner, and more powerful. Start by practicing methods like "map", "filter", "pluck", and "reduce", then explore the rest of the Laravel Collection methods. With time, you’ll naturally use them to write more elegant solutions.