How to Implement Yajra Datatables Server Side in Laravel 8

How to Implement Yajra Datatables Server Side in Laravel 8

Admin
Admin・ 21 Agustus 2021
9 min read ・ 21601 views
Series: Laravel Livewire

Laravel Datatables - Do you have thousands of data in the database? Do you want to display it with a more user friendly display? If the answer is yes, we can use the laravel datatables package to create dynamic tables to display thousands of these data.

Well, in this article I will share a tutorial on how to use the laravel datatables package in laravel version 8 to display dynamic data with several features such as pagination, instant search, multi-column ordering and others.

Ok, let's start coding 🚀

Step 1: Install Laravel 8

laravel new laravel-datatables

The first step we will do in this tutorial is to install the latest version of laravel (currently version 8). To install laravel, we can use the laravel installer with the command as above or install laravel with composer with the command as below.

composer create-project laravel/laravel laravel-datatables

We are free to use whichever way we like to install laravel project, whether with laravel installer or with composer. From the two examples of the command above, if executed, it will create or generate a laravel project with the name laravel-datatables. If the installation process is complete, open the project with the cd laravel-datatables command.

Step 2: Create New Database & Setup .ENV

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_datatables
DB_USERNAME=root
DB_PASSWORD=

Finished in the first step, we continue in the second step, which is to create a new database to accommodate the dummy data that we will create in the next step using the factory. When you have finished creating a new database, don't forget to adjust the DB_DATABASE in the .ENV file as in the example above.

Step 3: Install Laravel Datatables Package

composer require yajra/laravel-datatables-oracle:"~9.0"

In this tutorial we will use the laravel datatables package from yajra. This package is made to handle server side performance of jQuery plugin datatables via AJAX using Eloquent ORM, Query Builder or Collection. Please open the terminal again and run the above command to install the laravel datatables package.

Step 4: Edit User Migration

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('gender');
            $table->string('email')->unique();
            $table->string('phone');
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
} 

By default, Laravel has provided a migration file to create a user table with fields name, email, email_verified_at and others. The file is located in the database/migration/{timestamp}_create_users_table.php directory. So in this file, we're going to update it a bit by adding the gender and phone fields. Adjust the code in the migration file with the code as above.

Step 5: Create Dummy Data

<?php

namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class UserFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = User::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => $this->faker->name(),
            'gender' => $this->faker->randomElement(['male', 'female']),
            'email' => $this->faker->unique()->safeEmail(),
            'phone' => $this->faker->phoneNumber(),
            'email_verified_at' => now(),
            'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
            'remember_token' => Str::random(10),
        ];
    }

    /**
     * Indicate that the model's email address should be unverified.
     *
     * @return \Illuminate\Database\Eloquent\Factories\Factory
     */
    public function unverified()
    {
        return $this->state(function (array $attributes) {
            return [
                'email_verified_at' => null,
            ];
        });
    }
}

We will create dummy data for the user table and will display the data from the user table using the laravel datatables package. Open the file located in database/factories/UserFactory.php and adjust the existing code with the code as above.

php artisan tinker
User::factory()->count(30)->create()

Then we will execute the UserFactory file using tinker. Open a terminal, then run the command php artisan tinker and followed by the command User::factory()->count(30)->create() to start generating 30 dummy user data.

Step 6: Define Route

<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;
use Yajra\Datatables\Datatables;
use App\Models\User;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('getUser', function (Request $request) {
    if ($request->ajax()) {
            $data = User::latest()->get();
            return DataTables::of($data)
                ->addIndexColumn()
                ->addColumn('action', function($row){
                    $actionBtn = '<a href="javascript:void(0)" class="edit btn btn-success btn-sm">Edit</a> <a href="javascript:void(0)" class="delete btn btn-danger btn-sm">Delete</a>';
                    return $actionBtn;
                })
                ->rawColumns(['action'])
                ->make(true);
        }
})->name('user.index'); 

In this tutorial we are not working in Controller because we will be creating logic and implementing laravel datatables in routes. Please open the route/web.php file then adjust the existing code with the code as above.

In this route, we will use request, yajra datatables and user model. In route::('/') nothing changes because we will still use welcome.blade.php for display when laravel project is run.

We need to add a new route with laravel datatables logic to display users data using laravel datatables and we will call it in welcome.blade.php file in the next step.

Step 7: Setup Blade View

<!DOCTYPE html>
<html>
    <head>
        <title>How to Use Yajra Datatables in Laravel 8</title>
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"/>
        <link href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet">
        <link href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css" rel="stylesheet">
    </head>
    <body>
        <div class="container mt-5">
            <h1 class="mb-4 text-center">How to Use Yajra Datatables in Laravel 8</h1>
            <table class="table table-bordered yajra-datatable">
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Name</th>
                        <th>Gender</th>
                        <th>Email</th>
                        <th>Phone</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
    <script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
    <script type="text/javascript">
        $(function () {
          
          var table = $('.yajra-datatable').DataTable({
              processing: true,
              serverSide: true,
              ajax: "{{ route('user.index') }}",
              columns: [
                  {data: 'DT_RowIndex', name: 'DT_RowIndex'},
                  {data: 'name', name: 'name'},
                  {data: 'gender', name: 'gender'},
                  {data: 'email', name: 'email'},
                  {data: 'phone', name: 'phone'},
                  {
                      data: 'action', 
                      name: 'action', 
                      orderable: true, 
                      searchable: true
                  },
              ]
          });
          
        });
    </script>
</html>

In the last step, please open the welcome.blade.php file, then copy all the code above and replace it in the welcome.blade.php file. With the code above, we change the welcome view which is the default from laravel to a table view that contains user data. Then we insert an AJAX script that calls the route with the name user.index that we created in the previous step.

Step 8: Laravel Datatables Testing

Okay, after going through the steps starting from installing laravel, installing laravel datatables to setting up blade view to create a user table view, now it's time to test. To see if the laravel datatables program is working, we simply run our laravel project with the php artisan serve command and then open it in a browser with the URL 127.0.0.1:8000 or laravel-datatables.test.

Good luck, hopefully this article can be useful and see you in the next article 🚀 🚀 🚀

 

Credit: Business analytics illustrations by Storyset

Tinggalkan Komentar
Loading Comments