Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

pthai-it-dev's avatar

How to generate meta and links properties of Paginator without using Laravel API resource.

I am using paginate on the query builder. The result returned is an array of stdClass instances. So I can not pass it to API resource. But I want the response has meta and links properties just like when I use API resource to format data. What should I do?

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

You can manually create the meta and links properties using the Paginator instance. Here's an example:

$perPage = 10;
$page = request()->get('page', 1);
$offset = ($page - 1) * $perPage;

$query = DB::table('my_table')->offset($offset)->limit($perPage)->get();

$total = DB::table('my_table')->count();

$paginator = new LengthAwarePaginator($query, $total, $perPage, $page);

$meta = [
    'current_page' => $paginator->currentPage(),
    'from' => $paginator->firstItem(),
    'last_page' => $paginator->lastPage(),
    'path' => request()->url(),
    'per_page' => $perPage,
    'to' => $paginator->lastItem(),
    'total' => $paginator->total(),
];

$links = [
    'first' => $paginator->url(1),
    'last' => $paginator->url($paginator->lastPage()),
    'prev' => $paginator->previousPageUrl(),
    'next' => $paginator->nextPageUrl(),
];

$response = [
    'data' => $query,
    'meta' => $meta,
    'links' => $links,
];

return response()->json($response);

In this example, we manually create a LengthAwarePaginator instance using the query builder result, total count, and pagination parameters. Then, we create the meta and links properties using the paginator instance methods. Finally, we return a JSON response with the data, meta, and links properties.

1 like

Please or to participate in this conversation.