Stop Writing Nested Loops in Laravel Collections Using mapToGroups()

Group transformed data in a single step without manual loops.

  • 22 Jun, 2026
  • 37 Views

Stop Writing Nested Loops in Laravel Collections Using mapToGroups()

Laravel Collection's mapToGroups() method allows you to transform and group items simultaneously. It's perfect for creating lookup tables, grouped reports, and organizing data without writing nested loops.

Basic Example

Suppose you have:

$employees = collect([
    ['name' => 'John', 'department' => 'IT'],
    ['name' => 'Jane', 'department' => 'HR'],
    ['name' => 'Mike', 'department' => 'IT'],
]);

Using:

$employees->mapToGroups(function ($employee) {
    return [
        $employee['department'] => $employee['name']
    ];
});

Result:

[
    'IT' => ['John', 'Mike'],
    'HR' => ['Jane'],
]

Why Not groupBy()?

With groupBy():

$products->groupBy('category');

You still get complete models.

With mapToGroups():

$products->mapToGroups(...)

You decide exactly what gets stored.

Why Use mapToGroups()?

It helps you:

  • Avoid nested loops
  • Transform and group in one step
  • Build lookup structures
  • Prepare report data efficiently

When to Use It

Use mapToGroups() when:

  • Creating reports
  • Building dropdown data
  • Grouping labels
  • Preparing API responses

Share: