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 the ability to transform paginator items #34657

Merged
merged 2 commits into from
Oct 5, 2020
Merged

[8.x] Add the ability to transform paginator items #34657

merged 2 commits into from
Oct 5, 2020

Conversation

reinink
Copy link
Contributor

@reinink reinink commented Oct 3, 2020

This PR adds the ability to transform paginator items via a new through() method, which returns an instance of the Paginator, and not the underlying Collection.

Here's an example use case:

return Inertia::render('Contacts/Index', [
    'contacts' => Contact::paginate()->through(function ($contact) {
        return [
            'id' => $contact->id,
            'name' => $contact->name,
            'phone' => $contact->phone,
            'city' => $contact->city,
            'organization' => optional($contact->organization)->only('name')
        ];
    }),
]);

This is needed since it's very common to want to map the data prior to the paginator being JSON encoded. However, right now there is no way to do that, since calling map() or transform() on the paginator object forwards calls to the underlying collection, which returns an instance of the Collection, not the Paginator.

Meaning, if you call $paginator->transform(), you'll only get the data back, and not the paginator toArray() structure (data, links, current_page, total, etc).

We could also call this transformItems(), but I think through() is more expressive.

@deleugpn
Copy link
Contributor

deleugpn commented Oct 4, 2020

I just built a component in front of JsonResource to do something pretty similar to this, but much more complex than this. I think I'll be able to simplify some of my APIs with this as well. Seems low-cost, high-benefit.

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.

3 participants