DEV Community

Aleson França
Aleson França

Posted on

Exploring Laravel Collections: A Simple Guide

Laravel collections are one of the most powerful tools in the framework. They extend the Illuminate\Support\Collection class and provide a smooth interface to manipulate arrays and objects in an expressive way.

Creating Collections

You can create a collection from an array using the collect() method:

$collection = collect([1, 2, 3, 4, 5]);
Enter fullscreen mode Exit fullscreen mode

Key Collection Methods

Below, we'll dive into some of the most useful and powerful methods.

map() - Transforming Values

The map() method lets you apply a function to each item in the collection.

$doubled = collect([1, 2, 3])->map(fn($num) => $num * 2);
// [2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

filter() - Filtering Values

Filters the collection items based on a condition.

$evenNumbers = collect([1, 2, 3, 4, 5])->filter(fn($num) => $num % 2 === 0);
// [2, 4]
Enter fullscreen mode Exit fullscreen mode

reduce() - Reducing to a Single value

Useful for collapsing the collection into a single accumulated value.

$sum = collect([1, 2, 3, 4])->reduce(fn($carry, $num) => $carry + $num, 0);
// 10
Enter fullscreen mode Exit fullscreen mode

pluck() - Extracting Values from a Field

The pluck() method allows you to extract values from a specific key in a collection of arrays or objects.

$users = collect([
    ['name' => 'Alice', 'age' => 28],
    ['name' => 'Bob', 'age' => 34],
]);

$names = $users->pluck('name');
// ['Alice', 'Bob']
Enter fullscreen mode Exit fullscreen mode

groupBy() - Grouping Data

The groupBy() method allows you to group collection items based on a given key or callback function.

$users = collect([
    ['name' => 'Alice', 'group' => 'A'],
    ['name' => 'Bob', 'group' => 'B'],
    ['name' => 'Charlie', 'group' => 'A']
]);

$groups = $users->groupBy('group');
// Group A: Alice, Charlie
// Group B: Bob
Enter fullscreen mode Exit fullscreen mode

chunk() - Splitting the Collection into Smaller Pieces

The chunk() method breaks the collection into multiple smaller collections of a given size.

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8]);
$chunks = $collection->chunk(3);

// [[1, 2, 3], [4, 5, 6], [7, 8]]
Enter fullscreen mode Exit fullscreen mode

each() - Iterating Over the Collection

The each() method allows you to loop through each item in the collection and perform an action on it.

collect([1, 2, 3])->each(fn($num) => print($num));
// 1 2 3
Enter fullscreen mode Exit fullscreen mode

contains() - Checking if a value exists

The contains() method checks if a given item is present in the collection.

$exists = collect([1, 2, 3])->contains(2);
Enter fullscreen mode Exit fullscreen mode

pipe() - Passing the collection to a function

The pipe() method allows you to pass the entire collection into a function and return the result.

$result = collect([1, 2, 3])->pipe(function ($collection) {
    return $collection->sum();
});
// 6
Enter fullscreen mode Exit fullscreen mode

has() - Checking if a key exists

The has() method determines if a given key exists in the collection.

$collection = collect(['name' => 'Alice', 'age' => 28]);
$exists = $collection->has('age');
// true
Enter fullscreen mode Exit fullscreen mode

dot() - Converting a Multi-Dimensional Array to Dot Notation

The dot() method transforms nested arrays into a flat array using dot notation.

$collection = collect(['user' => ['name' => 'Alice', 'email' => 'alice@example.com']]);
$dot = $collection->dot();
// ['user.name' => 'Alice', 'user.email' => 'alice@example.com']
Enter fullscreen mode Exit fullscreen mode

isEmpty() - Checking if the collection is empty

The isEmpty() method returns true if the collection has no items.

$empty = collect([])->isEmpty();
// true
Enter fullscreen mode Exit fullscreen mode

Conclusion

Laravel Collections make array manipulation way more intuitive and expressive. If you want to write cleaner and more elegant code, mastering them is a must!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay