Skip to content

[5.5] Document Collection::mapToGroups() method #3696

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions collections.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ For the remainder of this documentation, we'll discuss each method available on
[keys](#method-keys)
[last](#method-last)
[map](#method-map)
[mapToGroups](#method-maptogroups)
[mapWithKeys](#method-mapwithkeys)
[max](#method-max)
[median](#method-median)
Expand Down Expand Up @@ -756,6 +757,43 @@ The `map` method iterates through the collection and passes each value to the gi

> {note} Like most other collection methods, `map` returns a new collection instance; it does not modify the collection it is called on. If you want to transform the original collection, use the [`transform`](#method-transform) method.

<a name="method-maptogroups"></a>
#### `mapToGroups()` {#collection-method}

The `mapToGroups` method groups the collection's items by the given callback. The callback should return an associative array containing a single key / value pair, thus forming a new collection of grouped values:

$collection = collect([
[
'name' => 'John Doe',
'department' => 'Sales',
],
[
'name' => 'Jane Doe',
'department' => 'Sales',
],
[
'name' => 'Johnny Doe',
'department' => 'Marketing',
]
]);

$grouped = $collection->mapToGroups(function ($item, $key) {
return [$item['department'] => $item['name']];
});

$grouped->toArray();

/*
[
'Sales' => ['John Doe', 'Jane Doe'],
'Marketing' => ['Johhny Doe'],
]
*/

$grouped->get('Sales')->all();

// ['John Doe', 'Jane Doe']

<a name="method-mapwithkeys"></a>
#### `mapWithKeys()` {#collection-method}

Expand Down
1 change: 1 addition & 0 deletions eloquent-collections.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ All Eloquent collections extend the base [Laravel collection](/docs/{{version}}/
[keys](/docs/{{version}}/collections#method-keys)
[last](/docs/{{version}}/collections#method-last)
[map](/docs/{{version}}/collections#method-map)
[mapToGroups](/docs/{{version}}/collections#method-maptogroups)
[mapWithKeys](/docs/{{version}}/collections#method-mapwithkeys)
[max](/docs/{{version}}/collections#method-max)
[median](/docs/{{version}}/collections#method-median)
Expand Down