How to Create Pagination API in Laravel

AuthorSumit Dey Sarkar

Pubish Date22 Mar 2023

categoryLaravel

In this tutorial we will learn how to create pagination API in laravel.

 

How to Create Pagination API in Laravel

To create a pagination API in Laravel, you can follow the steps below:

 

Step 1: Create a Route

Create a route in your routes/api.php file that maps to your controller method that will handle the pagination logic. For example:

Route::get('users', 'UserController@index');

 

Step 2: Create a Controller

Create a controller using the artisan command:

php artisan make:controller UserController

In your UserController, add the index method that will handle the pagination logic:

public function index(Request $request)
{
    $users = User::paginate($request->input('per_page', 10));

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

 

Step 3: Send Request

Send a GET request to the /api/users endpoint with the per_page query parameter to specify the number of results per page. For example:

GET /api/users?per_page=20

This will return a JSON response with the paginated data.

 

Note: The paginate() method automatically adds the necessary links to navigate through the pages.

 

That's it! You now have a pagination API in Laravel.

Comments 0

Leave a comment