Logo

dev-resources.site

for different kinds of informations.

Create a pagination API with Laravel

Published at
7/22/2024
Categories
pagination
laravel
Author
stackpuz
Categories
2 categories in total
pagination
open
laravel
open
Author
8 person written this
stackpuz
open
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 mode Exit 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 mode Exit 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=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=example
DB_USERNAME=root
DB_PASSWORD=

SESSION_DRIVER=file
Enter fullscreen mode Exit fullscreen mode

We also set SESSION_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.

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::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 mode Exit 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.

<?php

use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('index');
});
Enter fullscreen mode Exit fullscreen mode

api.php

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

<?php

use App\Http\Controllers\ProductController;

Route::get('/products', [ProductController::class, 'index']);
Enter fullscreen mode Exit fullscreen mode

Product.php

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

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $table = 'Product';
    protected $primaryKey = 'id';
}
Enter fullscreen mode Exit 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.

<?php

namespace App\Http\Controllers;

use App\Models\Product;

class ProductController {

    public function index()
    {
        $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 mode Exit fullscreen mode

We utilize the query string to get $size, $order, $direction information and create the paginated data by using the paginate($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><a target="_blank" href="/api/products">Default</a></li>
        <li><a target="_blank" href="/api/products?page=2">Page 2</a></li>
        <li><a target="_blank" href="/api/products?page=2&size=25">Page 2 and Size 25</a></li>
        <li><a target="_blank" href="/api/products?page=2&size=25&order=name">Page 2 and Size 25 and Order by name</a></li>
        <li><a target="_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 mode Exit fullscreen mode

Run project

php artisan serve
Enter fullscreen mode Exit fullscreen mode

Open the web browser and goto http://localhost:8000

You will find this test page.

test page

Testing

Testing without any parameters

Click the "Default" link, and it will open the URL http://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 URL http://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 URL http://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 URL http://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 URL http://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

pagination Article's
30 articles in total
Favicon
CREATE Dynamic Pagination in JUST 20 Minutes with HTML, CSS and JavaScript!
Favicon
How to Paginate API Responses in Go
Favicon
Implement Paging, Sorting, and Searching in API (C#) andΒ angular
Favicon
Implementing the List Projection Class in C#
Favicon
Mastering Paginated API Calls in React for Optimized Data Fetching
Favicon
From Frontend to Backend: Build Scalable Pagination for Web Applications
Favicon
Pagination
Favicon
Completing the Paginator Class in C#
Favicon
Designing an Abstract Collection Interface for Pagination in C#
Favicon
Optimizing Pagination in PostgreSQL: OFFSET/LIMIT vs. Keyset
Favicon
Create a pagination API with FastAPI
Favicon
Check Pagination in .NET: With and Without Entity Framework
Favicon
Pagination CDN setup guide for ejs template engine.
Favicon
Unleashing MongoDB: Why Cursor-Based Pagination Outperforms Offset-Based Pagination Every Time!
Favicon
How to Paginate Multiple Lists on the Same Blade File in Laravel 11 with Bootstrap 5 and Tailwind CSS
Favicon
NPM Package & CDN for Pagination in Javascript / Nodejs
Favicon
Cursor Pagination Example
Favicon
Create a pagination API with .NET
Favicon
Create a pagination API with Go
Favicon
Create a pagination API with Express
Favicon
Gorm Pagination With Ease
Favicon
Create a pagination API with Laravel
Favicon
Create a pagination API with Spring Boot
Favicon
A Detailed Tutorial on Pagination for ASP.NET Core Web APIs πŸš€
Favicon
Pagination in C#: Complete Guide with Easy Code Examples πŸ“š
Favicon
Building custom pagination component with Angular
Favicon
Customizing API Resource Pagination Structure
Favicon
A Light-hearted Look at Pagination Optimization
Favicon
Implementando Infinite Scroll Pagination com Riverpod
Favicon
Avoiding Re-render on Pagination with Relay

Featured ones: