25 Aug 2024

Laravel 11 Datatable Server Side Pagination

Laravel 11 Datatable Server Side Pagination
Hello Laravel Enthusiasts!
In this tutorial, we will explore how to implement server-side pagination with Laravel and jQuery for dynamic web applications. Server-side pagination is crucial when dealing with large datasets, as it allows for efficient data retrieval and improved performance. By combining the powerful Laravel framework with the flexibility of jQuery, we can create a seamless user experience with enhanced search capabilities. Let’s dive into the step-by-step process of implementing this functionality.
DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, and will add advanced interaction controls to any HTML table.
Step 1: Install Laravel 11 Application
First, we need to install a new Laravel 11 application. Run the following command in your terminal:
 composer create-project laravel/laravel laravel-11-user-app   
Step 2: Configure the .env File
Next, we need to set up the database connection in the .env file. Open the file and modify the following lines according to your database credentials:

  DB_CONNECTION=mysql
  DB_HOST=127.0.0.1
  DB_PORT=3306
  DB_DATABASE=laravel_11
  DB_USERNAME=root
  DB_PASSWORD=root                                   
                
Step 3: Create a Model and Migration
Create a model and migration for user information using the following command:
  php artisan make:model User -m 
Update the migration file to define the users table:
 
  use Illuminate\Database\Migrations\Migration;
  use Illuminate\Database\Schema\Blueprint;
  use Illuminate\Support\Facades\Schema;
  
  return new class extends Migration
  {
      /**
        * Run the migrations.
        */
      public function up(): void
      {
          Schema::create('users', function (Blueprint $table) {
              $table->id();
              $table->string('name');
              $table->string('email')->unique();
              $table->string('phone');
              $table->timestamps();
          });
      }
  
      /**
        * Reverse the migrations.
        */
      public function down(): void
      {
          Schema::dropIfExists('users');
      }
  };  
            
Create the User model:
 
  namespace App\Models;

  use Illuminate\Database\Eloquent\Factories\HasFactory;
  use Illuminate\Database\Eloquent\Model;
  
  class User extends Model
  {
      use HasFactory;
      protected $guarded = [];
  }
          
Run the migration to create the users table:
 php artisan migrate  
Create a User Factory for generating dummy data:
 php artisan make:factory UserFactory  
Update the factory file:

  namespace Database\Factories;

  use Illuminate\Database\Eloquent\Factories\Factory;
  
  /**
    * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
    */
  class UserFactory extends Factory
  {
      /**
        * Define the model's default state.
        *
        * @return array
        */
      public function definition(): array
      {
          return [
              'name' => fake()->name(),
              'email' => fake()->unique()->safeEmail(),
              'phone' => fake()->phoneNumber(),
          ];
      }
  }  
        
Generate dummy records using Tinker:

  php artisan tinker
  App\Models\User::factory()->count(150)->create();          
        
Step 4: Create Controller
Create a controller to handle user-related requests:
php artisan make:controller UserController 
Update the UserController:

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\DB;

    class UserController extends Controller
    {
        public function index()
        {
            return view('users');
        }

        public function getUsers(Request $request)
        {
            // Page Length
            $pageNumber = ($request->start / $request->length) + 1;
            $pageLength = $request->length;
            $skip = ($pageNumber - 1) * $pageLength;

            // Page Order
            $orderColumnIndex = $request->order[0]['column'] ?? '0';
            $orderBy = $request->order[0]['dir'] ?? 'desc';

            // get data from users table
            $query = DB::table('users')->select('*');

            // Search
            $search = $request->search;
            $query = $query->where(function ($query) use ($search) {
                $query->orWhere('name', 'like', "%" . $search . "%");
                $query->orWhere('email', 'like', "%" . $search . "%");
                $query->orWhere('phone', 'like', "%" . $search . "%");
            });

            $orderByName = 'name';
            switch ($orderColumnIndex) {
                case '0':
                    $orderByName = 'name';
                    break;
                case '1':
                    $orderByName = 'email';
                    break;
                case '2':
                    $orderByName = 'phone';
                    break;
            }
            $query = $query->orderBy($orderByName, $orderBy);
            $recordsFiltered = $recordsTotal = $query->count();
            $users = $query->skip($skip)->take($pageLength)->get();

            return response()->json(["draw" => $request->draw, "recordsTotal" => $recordsTotal, "recordsFiltered" => $recordsFiltered, 'data' => $users], 200);
        }
    }
    
Step 5: Define Routes
Define the routes in the web.php file:

  use App\Http\Controllers\UserController;

  Route::get('/', [UserController::class, 'index'])->name('home');
  
  Route::post('/get-users', [UserController::class, 'getUsers'])->name('getUsers');
            
        
Step 6: Create View
Create the users.blade.php file with a table to display user information and integrate jQuery DataTables for server-side pagination and search functionality.

  <!doctype html>
  <html lang="en">
  
  <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <meta name="csrf-token" content="{{ csrf_token() }}" />
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
      <title>Laravel 11 Datatable Server Side Pagination - User Information</title>
  </head>
  
  <body>
      <div class="container">
          <div class="row">
              <div class="col-12 my-5">
                  <h3>Laravel 11 Datatable Server Side Pagination - User Information</h3>
              </div>
              <div class="col-12">
                  <table id="datatable" class="table" style="width:100%">
                      <thead class="table-dark">
                          <tr>
                              <td>Name</td>
                              <td>Email</td>
                              <td>Phone</td>
                          </tr>
                      </thead>
                  </table>
              </div>
          </div>
      </div>
  
      <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
      <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
      <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
      <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap4.min.js"></script>
  
      <script>
          $.ajaxSetup({
              headers: {
                  'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
              }
          });
          $(document).ready(function () {
              $('#datatable').DataTable({
                  processing: true,
                  serverSide: true,
                  ajax: {
                      url: "{{ route('getUsers') }}",
                      type: "POST",
                      data: function (data) {
                          data.search = $('input[type="search"]').val();
                      }
                  },
                  order: [{{ '1' }}, {{ 'DESC' }}],
                  pageLength: 10,
                  searching: true,
                  columns: [
                      { data: 'name' },
                      { data: 'email' },
                      { data: 'phone' }
                  ]
              });
          });
      </script>
  </body>
  
  </html>          
            
        
Step 7: Run the Laravel 11 Application
Finally, start your Laravel application with:
  php artisan serve 
Read Also:


Share:
...