VertexBuffer's avatar

How to modify Eloquent pagination data and retain pagination information?

So I'm aware you can do something like;

        $model = Model::latest()->paginate(10);
        $model->getCollection()
            ->transform(function ($model)
            {
                return [
                    'id' => $model->id,
                    'title' => $model->title,
            'created_at' => $model->created_at
                ];
            });

But in order to persist the pagination data such as total, next_page, etc... you have to do it as 2 separate function calls and you can't chain it. This bothers me because it seems unnecessary and messy.

Is it possible I can do this is a simpler way? Is it also possible for me to somehow drop this?

                return [
                    'id' => $model->id,
                    'title' => $model->title,
            'created_at' => $model->created_at
                ];

As I find myself needing to write every attribute which is incredibly tedious if all I'm trying to do is say mutate the created_at attribute to be a readable format.

0 likes
5 replies
VertexBuffer's avatar

@bobbybouwmann

Is it possible you can give an example of how to use this with pagination? I've read the docs and they aren't making too much sense to me. I tried generating a ResourceCollection and implementing it in the way the docs recommend but when I try use it, it doesn't include the pagination data and it also nulls all the attributes?

Thanks.

bobbybouwmann's avatar

@zyxxyzyxz Aah I think I miss read your question. API resources only generate pagination in JSON format. You can see an example here: https://laravel.com/docs/master/eloquent-resources#pagination

You can't use that with the pagination functionality that you might use in your views. If you want to use this in your views you have to build up the pagination object yourself. Here is an example: https://laracasts.com/discuss/channels/eloquent/paginate-eloquent-collection

VertexBuffer's avatar

@bobbybouwmann

Can you elaborate? I'm using Inertia, not blade. So JSON is fine. I'm just unsure of how to do it because the link you put doesn't really explain how to achieve that, just the result.

bobbybouwmann's avatar
Level 88

Basically you need to do something like this

$foos = Foo::paginate();

return Inertia::render('Foo', [
    'foo' => FooResource::collection($foos),
    'pagination' => [
        'current' => $foos->currentPage(),
        'last' => $foos->lastPage(),
        'base' => $foos->url(1),
        'next' => $foos->nextPageUrl(),
        'prev' => $foos->previousPageUrl(),
    ],
]);

Please or to participate in this conversation.