DeveloperBreeze

Laravel Programming Tutorials, Guides & Best Practices

Explore 51+ expertly crafted laravel tutorials, components, and code examples. Stay productive and build faster with proven implementation strategies and design patterns from DeveloperBreeze.

Building a Custom Pagination System for API Responses

Tutorial November 16, 2024
php

Modify the query to use a cursor:

   public function index(Request $request)
   {
       $limit = $request->get('limit', 10);
       $cursor = $request->get('cursor');

       $query = Post::query();

       if ($cursor) {
           $query->where('id', '>', $cursor); // Fetch items after the cursor
       }

       $posts = $query->orderBy('id')->take($limit + 1)->get();

       $nextCursor = $posts->count() > $limit ? $posts->last()->id : null;

       return response()->json([
           'data' => $posts->take($limit), // Return only the requested number of items
           'meta' => [
               'limit' => $limit,
               'next_cursor' => $nextCursor,
           ],
       ]);
   }