Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

StackPuz
StackPuz

Posted on • Originally published atblog.stackpuz.com on

Create a pagination API with Laravel

Pagination API with Laravel

Splitting larger content into distinct pages is known as pagination. This approach significantly enhances the user experience and speeds up the loading of web pages. This example will demonstrate how to create a pagination API using Laravel and use MySQL as a database.

Prerequisites

  • Composer
  • PHP 8.2
  • MySQL

Setup project

composer create-project laravel/laravel laravel_api 11.0.3
Enter fullscreen modeExit fullscreen mode

Create a testing database named "example" and run the database.sql file to import the table and data.

Project structure

├─ .env├─ app│  ├─ Http│  │  └─ Controllers│  │     └─ ProductController.php│  └─ Models│     └─ Product.php├─ bootstrap│  └─ app.php├─ resources│  └─ views│     └─ index.php└─ routes   ├─ api.php   └─ web.php
Enter fullscreen modeExit fullscreen mode

*This project structure will show only files and folders that we intend to create or modify.

Project files

.env

This file is the Laravel configuration file and we use it to keep the database connection information.

DB_CONNECTION=mysqlDB_HOST=localhostDB_PORT=3306DB_DATABASE=exampleDB_USERNAME=rootDB_PASSWORD=SESSION_DRIVER=file
Enter fullscreen modeExit fullscreen mode

We also setSESSION_DRIVER=file to change the session driver from database to file.

app.php

This file is the Laravel application configuration file, and we only added the API routing file here.

<?phpuseIlluminate\Foundation\Application;useIlluminate\Foundation\Configuration\Exceptions;useIlluminate\Foundation\Configuration\Middleware;returnApplication::configure(basePath:dirname(__DIR__))->withRouting(web:__DIR__.'/../routes/web.php',api:__DIR__.'/../routes/api.php',commands:__DIR__.'/../routes/console.php',health:'/up',)->withMiddleware(function(Middleware$middleware){//})->withExceptions(function(Exceptions$exceptions){//})->create();
Enter fullscreen modeExit fullscreen mode

web.php

This file defines the route URL for the Laravel web application. We just changed the default file from welcome.php to index.php.

<?phpuseIlluminate\Support\Facades\Route;Route::get('/',function(){returnview('index');});
Enter fullscreen modeExit fullscreen mode

api.php

This file defines the route URL for the Laravel API. We define our API route here.

<?phpuseApp\Http\Controllers\ProductController;Route::get('/products',[ProductController::class,'index']);
Enter fullscreen modeExit fullscreen mode

Product.php

This file defines the Eloquent Model information that maps to our database table named "Product".

<?phpnamespaceApp\Models;useIlluminate\Database\Eloquent\Model;classProductextendsModel{protected$table='Product';protected$primaryKey='id';}
Enter fullscreen modeExit fullscreen mode

*To keep the code simple, we define only a few pieces of information here. This is enough for our API.

ProductController.php

This file is used to handle incoming requests and produce the paginated data for the client.

<?phpnamespaceApp\Http\Controllers;useApp\Models\Product;classProductController{publicfunctionindex(){$size=request()->input('size')??10;$order=request()->input('order')??'id';$direction=request()->input('direction')??'asc';$query=Product::query()->select('id','name','price')->orderBy($order,$direction);$products=$query->paginate($size);return$products->items();}}
Enter fullscreen modeExit fullscreen mode

We utilize the query string to get$size, $order, $direction information and create the paginated data by using thepaginate($size) method.

index.php

Instead of entering the URL manually to test our API, we used this file to create links for easier testing.

<!DOCTYPE html><head></head><body><ul><li><atarget="_blank"href="/api/products">Default</a></li><li><atarget="_blank"href="/api/products?page=2">Page 2</a></li><li><atarget="_blank"href="/api/products?page=2&size=25">Page 2 and Size 25</a></li><li><atarget="_blank"href="/api/products?page=2&size=25&order=name">Page 2 and Size 25 and Order by name</a></li><li><atarget="_blank"href="/api/products?page=2&size=25&order=name&direction=desc">Page 2 and Size 25 and Order by name descending</a></li></ul></body></html>
Enter fullscreen modeExit fullscreen mode

Run project

php artisan serve
Enter fullscreen modeExit fullscreen mode

Open the web browser and gotohttp://localhost:8000

You will find this test page.

test page

Testing

Testing without any parameters

Click the "Default" link, and it will open the URLhttp://localhost:8000/api/products

default test

The API will return paginated data with default parameters (page = 1 and size = 10).

Page index test

Click the "Page 2" link, and it will open the URLhttp://localhost:8000/api/products?page=2

page index test

The API will return paginated data on the second page, starting with product id 11

Page size test

Click the "Page 2 and Size 25" link, and it will open the URLhttp://localhost:8000/api/products?page=2&size=25

page size test

The API will return paginated data on the second page by starting with product id 26 because the page size is 25.

Order test

Click the "Page 2 and Size 25 and Order by name" link, and it will open the URLhttp://localhost:8000/api/products?page=2&size=25&order=name

order test

The API will return paginated data on the second page, but the product order is based on the product name.

Descending order test

Click the "Page 2 and Size 25 and Order by name descending" link, and it will open the URLhttp://localhost:8000/api/products?page=2&size=25&order=name&direction=desc

descending order test

The API will return paginated data on the second page, but the product order is based on the product name in descending order.

Conclusion

In this article, you have learned how to create and setup the Laravel application in order to implement the pagination API. The pagination approach will enhance the user experience and speed up your Laravel API. If you like the article, please share it with your friends.

Source code:https://github.com/stackpuz/Example-Pagination-Laravel-11

Create a CRUD Web App in Minutes:https://stackpuz.com

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Create a CRUD Web App in Minutes.
  • Location
    Chai Nat, Thailand
  • Joined

More fromStackPuz

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp