Using Laravel Collections (map, filter, pluck)

rafiqul
Rafiqul Hasan
Published on Sep, 25 2025 1 min read 0 comments
Text Image

# ๐Ÿ—‚ Using Laravel Collections (map, filter, pluck)

Laravelโ€™s **Collections** are powerful wrappers around arrays that make working with data super convenient. Instead of writing raw loops, you can use collection methods like `map`, `filter`, and `pluck` to transform data cleanly.  

---

## ๐Ÿ”ง What is a Collection?
A Collection is basically an array with extra helper methods. You can create one using:  

```php
use Illuminate\Support\Collection;
$numbers = collect([1, 2, 3, 4, 5]);

 

๐Ÿ”น 1. Using map()

map() transforms each item in the collection.

 

$numbers = collect([1, 2, 3]);

$doubled = $numbers->map(function ($num) {
    return $num * 2;
});

dd($doubled->all()); // [2, 4, 6]

๐Ÿ‘‰ Great for modifying values without changing the original array.

 

๐Ÿ”น 2. Using filter()

filter() removes items that donโ€™t match a condition.

 

$numbers = collect([1, 2, 3, 4, 5]);

$even = $numbers->filter(function ($num) {
    return $num % 2 === 0;
});

dd($even->all()); // [2, 4]

๐Ÿ‘‰ Useful for selecting only the data you need.

 

๐Ÿ”น 3. Using pluck()

pluck() extracts values from a given key in a collection of arrays or objects.

 

$users = collect([
    ['id' => 1, 'name' => 'Alice'],
    ['id' => 2, 'name' => 'Bob'],
]);

$names = $users->pluck('name');

dd($names->all()); // ['Alice', 'Bob']

๐Ÿ‘‰ Perfect for grabbing specific fields from a dataset.

 

๐ŸŽฏ Conclusion

Laravel Collections provide a cleaner, chainable way to work with data.

Use map() to transform items.

Use filter() to remove unwanted items.

Use pluck() to extract specific values.

Once you start using Collections, youโ€™ll rarely go back to writing raw PHP loops!

0 Comments