Collections in Laravel are "hidden gems": not everyone is using them. They are especially effective when performing MULTIPLE operations with data - so-called "chains". I've gathered 15 real-life examples from open-source Laravel projects. The goal is not only to show the Collection methods but also the practical scenarios of WHEN to use them.
This long tutorial is a text-version of my video course with the same examples.
So, let's dive into examples, one by one, with the links to the original sources.
Example 1: map + implode
Let's start this tutorial about Laravel Collection Chains with a very simple example, with a chain of two methods. The goal here is to show permissions divided by a new HTML tag.
Code:
1$role = Role::with('permissions')->first();2$permissionsListToShow = $role->permissions3 ->map(fn($permission) => $permission->name)4 ->implode("<br>");
The initial value of $role->permissions
is permission objects, and we are interested only in the name
field.
Then we do map
through those permissions, where we new collection containing only the names.
And finally after implode()
we get:
1"manage users<br>manage posts<br>manage comments"
The GitHub repository with code can be found here. Inspiration source: Bottelet/DaybydayCRM.
Example 2: map + max
You have an array of some kinds of scores, and then you have the collection of the scores from the database or from elsewhere.
Code:
1$hazards = [ 2 'BM-1' => 8, 3 'LT-1' => 7, 4 'LT-P1' => 6, 5 'LT-UNK' => 5, 6 'BM-2' => 4, 7 'BM-3' => 3, 8 'BM-4' => 2, 9 'BM-U' => 1,10 'NoGS' => 0,11 'Not Screened' => 0,12];13 14$score = Score::all()->map(function($item) use ($hazards) {15 return $hazards[$item->field];16})->max();
The initial value could be this:
And your goal is to find the highest value from that array, from those values of the scores.
After map()
, we return only the number from an array by score field.
And the last max()
only runs through all values and returns the maximum:
17
The GitHub repository with code can be found here. Inspiration source: Laracasts
Example 3: pluck + flatten
Initial data comes from config which has...