Skip to content
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

[8.x] Add query builder map method #36193

Closed
wants to merge 1 commit into from

Conversation

reinink
Copy link
Contributor

@reinink reinink commented Feb 9, 2021

This PR adds a new map() method to the Query/Builder and Eloquent/Builder classes (via the BuildsQueries trait). This method is similar to the each() query builder method, where it automatically chunks over the results. Here's how to use it:

return User::orderBy('name')->map(fn ($user) => [
    'id' => $user->id,
    'name' => $user->name,
]), 25);

The primary motivation here is to make it easier to chunk through query results while also performing a map. Previously, this was quite verbose to do (and required a temporary variable):

use Illuminate\Support\Collection;

$users = Collection::make();

User::orderBy('name')->each(function ($user) use ($users) {
    $users->push([
        'id' => $user->id,
        'name' => $user->name,
    ]);
}, 25);

return $users;

For what it's worth, I probably would have preferred the $count argument first (before the $callback), like the chunk() method, but I did it this way to match the each() method.

@taylorotwell
Copy link
Member

Merged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants