Laravel 11 API Resources: Customizing API Resource Collection Pagination

Raviya Technical
2 min readNov 6, 2024

This method accepts $paginated data and a $default array, which includes essential pagination details like links and meta keys.

Laravel Official Docs

Example User

public function index()
{
$records = User::paginate(15);
return new UserCollection($records);
}

app/Http/Resources/UserResource.php

<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;

class UserCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @return array<int|string, mixed>
*/
public function toArray(Request $request): array
{
return parent::toArray($request);
}
}

Adding this method Below class

public function paginationInformation($request, $paginated, $default)
{
$default['pagination']['current_page'] = $default['meta']['current_page'];
$default['pagination']['from'] = $default['meta']['from'];
$default['pagination']['last_page'] = $default['meta']['last_page'];
$default['pagination']['per_page'] = $default['meta']['per_page']…

--

--

Responses (2)