DEV Community

StackPuz
StackPuz

Posted on • Originally published at blog.stackpuz.com on

Create an API for AG-Grid with Laravel

AG-Grid with Laravel API

AG-Grid is a powerful JavaScript data grid library, ideal for creating dynamic and high-performance data tables with features like sorting, filtering, and pagination. In this article, we’ll implement an API in Laravel to support AG-Grid, enabling efficient server-side handling of data retrieval, filtering, and sorting. By combining AG-Grid with Laravel, we’ll achieve a seamless integration that ensures smooth performance even with large datasets.

Prerequisites

  • Composer
  • PHP 8.2
  • MySQL

Setup project

Create a new laravel 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=
Enter fullscreen mode Exit fullscreen mode

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 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

<?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';
        $search = request()->input('search');
        $query = Product::query()
            ->select('id', 'name', 'price')
            ->orderBy($order, $direction);
        if ($search) {
            $query->where('name', 'like', "%$search%");
        }
        $count = $query->count();
        $paginate = $query->paginate($size);
        return ['data' => $paginate->items(), 'count' => $count];
    }
}
Enter fullscreen mode Exit fullscreen mode

The ProductController.php file defines a controller in a Laravel application responsible for managing product-related requests. The index method retrieves a paginated list of products based on query parameters such as size, order, direction, and search. It constructs a query using Eloquent's Product model, allowing for sorting and filtering by product name. The method returns a JSON response containing the current page's product data and the total count of matching products, making it suitable for dynamic integration with front-end frameworks like AG-Grid.

index.php

<!DOCTYPE html>
<head>
    <script src="https://cdn.jsdelivr.net/npm/ag-grid-community/dist/ag-grid-community.min.js"></script>
</head>
<body>
    <div id="grid" class="ag-theme-alpine" style="height: 400px; width: 640px; margin: 1em"></div>
    <script>
        function getQuery(params) {
            let query = new URLSearchParams()
            let size = params.endRow - params.startRow
            let page = Math.floor(params.startRow / size) + 1
            query.append('page', page)
            query.append('size', size)
            if (params.sortModel.length) {
                let sort = params.sortModel[0]
                query.append('order', sort.colId)
                query.append('direction', sort.sort)
            }
            if (params.filterModel.name) {
                query.append('search', params.filterModel.name.filter)
            }
            return query.toString()
        }
        let columns = [
            { headerName: 'ID', field: 'id', sortable: true },
            {
                headerName: 'Name', field: 'name', sortable: true, filter: true,
                filterParams: {
                    filterOptions: ['contains'],
                    maxNumConditions: 1,
                }
            },
            { headerName: 'Price', field: 'price', sortable: true }
        ]
        let gridOptions = {
            columnDefs: columns,
            rowModelType: 'infinite',
            pagination: true,
            paginationPageSize: 20,
            cacheBlockSize: 20,
            datasource: {
                getRows: function (params) {
                    let query = getQuery(params)
                    fetch(`/api/products?${query}`)
                        .then(response => response.json())
                        .then(json => {
                            params.successCallback(json.data, json.count)
                        })
                }
            }
        }
        document.addEventListener('DOMContentLoaded', () => {
            agGrid.createGrid(document.querySelector('#grid'), gridOptions)
        })
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Theindex.php file sets up a web page that uses the AG-Grid library to display a dynamic data grid for products. It includes a grid styled with the AG-Grid theme and a JavaScript section that constructs query parameters for pagination, sorting, and filtering. The grid is configured with columns for ID, Name, and Price, and it fetches product data from an API endpoint based on user interactions. Upon loading, the grid is initialized, allowing users to view and manipulate the product list effectively.

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.

default test page

Testing

Page size test

Change page size by selecting 50 from the "Page Size" drop-down. You will get 50 records per page, and the last page will change from 5 to 2.

page size test

Sorting test

Click on the header of the first column. You will see that the id column will be sorted in descending order.

sorting test

Search test

Enter "no" in the search text-box of the "Name" column, and you will see the filtered result data.

search test

Conclusion

In conclusion, we’ve explored how to implement AG-Grid with Laravel to build a robust, efficient data grid solution. By leveraging Laravel’s backend capabilities, we enabled AG-Grid to handle server-side filtering, sorting, and pagination, ensuring smooth performance even with large datasets. This setup not only optimizes data management on the backend but also enhances the user experience on the frontend with dynamic and responsive data tables. With AG-Grid and Laravel working together, we’ve created a scalable and powerful grid system ready for real-world applications.

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

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

Top comments (0)