in General, Programming

How to implement DataTables server-side processing with Ajax pagination in Laravel

Hi, this is me again.. now I will show you an example of how to implement DataTables server-side processing with Ajax pagination in Laravel, so let’s start !

  1. Install DataTables:

First, you need to install DataTables. You can do this using npm:

npm install datatables.net --save
  1. Create a Route:

Create a Laravel route that will return the data for the DataTables table. The route should accept an optional start parameter, which specifies the starting row number for the query.

Route::get('datatable', 'DataController@datatable')->name('datatable');
  1. Create a Controller:

Create a controller that will handle the request for the DataTables data. In this example, the controller is named DataController.

php artisan make:controller DataController

In the DataController, create a method named datatable() that will return the data for the DataTables table:

public function datatable(Request $request)
{
    $query = DB::table('your_table')
        ->select('column1', 'column2', 'column3');

    $totalData = $query->count();

    $start = $request->input('start');
    $length = $request->input('length');

    $query->skip($start)->take($length);
    $data = $query->get();

    return response()->json([
        'draw' => $request->input('draw'),
        'recordsTotal' => $totalData,
        'recordsFiltered' => $totalData,
        'data' => $data
    ]);
}

This method returns the data for the DataTables table in JSON format. It uses the skip() and take() methods to paginate the query, based on the start and length parameters passed from the DataTables request. It also includes the total number of records (recordsTotal and recordsFiltered) and the data itself (data).

  1. Create a View:

Create a view that contains the HTML for the DataTables table.

<table id="datatable" class="table table-bordered">
    <thead>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
            <th>Column 3</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>

The id of the table must be set to datatable.

  1. Create a JavaScript file:

Create a JavaScript file that will initialize the DataTables table and handle the Ajax request. I set the csrf-token in the Meta Tag and authorization Bearer Token from current user login (optional), so it can be passed to the controller we created before.

$(document).ready(function() {
    var table = $('#datatable').DataTable({
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "{{ route('datatable') }}",
            "type": "GET",
            "data": function (d) {
                d.start = d.start || 0;
            },
            "headers": {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                'Authorization': 'Bearer {{ auth()->user()->api_token }}',
            },
        },
        "columns": [
            { "data": "dbcolumn1" },
            { "data": "dbcolumn2" },
            { "data": "dbcolumn3" }
        ]
    });
});

This code initializes the DataTables table and sets the processing and serverSide options to true. It also specifies the URL for the Ajax request ({{ route('datatable') }}) and sets the start parameter to 0 by default.

  1. Load the View:

Load the view in a Laravel route or controller. The view should include the HTML for the DataTables table and the JavaScript file.

return view('your-view');

That’s it! This example should help you get started with DataTables server-side processing with Ajax pagination in Laravel.

Write a Comment

Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.