You should use API Resources for this. This way you can transform the data in whatever you want and still have pagination support
Documentation: https://laravel.com/docs/6.x/eloquent-resources
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.
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.