Higher order collection methods

Collections have higher order methods, this are methods that can be chained , like groupBy() , map() ... Giving you a fluid syntax. This example calculates the price per group of products on an offer.

1$offer = [
2 'name' => 'offer1',
3 'lines' => [
4 ['group' => 1, 'price' => 10],
5 ['group' => 1, 'price' => 20],
6 ['group' => 2, 'price' => 30],
7 ['group' => 2, 'price' => 40],
8 ['group' => 3, 'price' => 50],
9 ['group' => 3, 'price' => 60]
10 ]
11];
12 
13$totalPerGroup = collect($offer['lines'])->groupBy('group')->map(fn($group) => $group->sum('price'));

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord