Laravel Collection is one of the most powerful features that beginner developers often underestimate. A Collection is an elegant wrapper for working with array data, providing dozens of built-in methods that make data manipulation easy without writing manual loops. After reading this article, you'll use Collection more intelligently and efficiently.
What Is a Laravel Collection?
A Collection is an instance of the Illuminate\Support\Collection class. Every Eloquent query that returns multiple rows automatically becomes a Collection. You can also create a Collection manually:
<?php
use Illuminate\Support\Collection;
// From a plain array
$collection = collect([1, 2, 3, 4, 5]);
// From an associative array
$users = collect([
['name' => 'Budi', 'age' => 25, 'city' => 'Jakarta'],
['name' => 'Ani', 'age' => 30, 'city' => 'Bandung'],
['name' => 'Caca', 'age' => 22, 'city' => 'Jakarta'],
['name' => 'Dodi', 'age' => 28, 'city' => 'Surabaya'],
]);
The map() Method — Transforming Data
map() iterates over each item and returns a new Collection of the transformed results:
// Convert all names to uppercase
$upperNames = $users->map(function ($user) {
return strtoupper($user['name']);
});
// Result: ['BUDI', 'ANI', 'CACA', 'DODI']
// With an arrow function (PHP 7.4+)
$prices = collect([10000, 25000, 15000]);
$discounted = $prices->map(fn($price) => $price * 0.9);
// Result: [9000, 22500, 13500]
This is only part of the article. For the full discussion, with examples and step-by-step details, you can read it on the original source:
How to Use Laravel Collections Effectively
More programming tutorials and developer tools are also available at dhiecoderweb.com.
Top comments (0)