DEV Community

Cover image for Laravel 8 - DataTables Server Side Rendering (5 easy steps) πŸ’ΎπŸ“ˆπŸ“Š
DaleLanto
DaleLanto

Posted on

Laravel 8 - DataTables Server Side Rendering (5 easy steps) πŸ’ΎπŸ“ˆπŸ“Š

Image description

DataTables has two fundamental modes of operation:

Client-side processing - where filtering, paging and sorting calculations are all performed in the web-browser.

Server-side processing - where filtering, paging and sorting calculations are all performed by a server.

What does DataTables Server Side Rendering mean?

Imagine about the situation when you see thousands, hundreds of thousands or millions of records, and you have to scan through every record to get the required information.

Seems like difficult right? But not only that imagine the toll it would give to the browser, you're website will literally blackout.

Here comes Datatables which makes our work less miserable and offers quick search, pagination, ordering, sortingfunctionalities to manage the data dynamically in the table.

I will also give tips on how to improve the performance and speed of your Datatables at the end!

Image description

Lets start creating our DataTables!

Step 1: Create the Laravel App and Install Yajra DataTables

Run the below-mentioned artisan command to install a new laravel application.

composer create-project laravel/laravel laravel-yajra-datatables --prefer-dist
Enter fullscreen mode Exit fullscreen mode

Then install the Yajra DataTable plugin in Laravel

composer require yajra/laravel-datatables-oracle
Enter fullscreen mode Exit fullscreen mode

Go to config/app.php file and paste this inside:

.....
.....
'providers' => [
    ....
    ....
    Yajra\DataTables\DataTablesServiceProvider::class,
]
'aliases' => [
    ....
    ....
    'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]
.....
.....
Enter fullscreen mode Exit fullscreen mode

Run vendor publish command

php artisan vendor:publish --provider="Yajra\DataTables\DataTablesServiceProvider"
Enter fullscreen mode Exit fullscreen mode

Easy right? Now that setups is done let's create our files!

Step 2: Create Model and Migrations

Run command to create a model

php artisan make:model Student -m
Enter fullscreen mode Exit fullscreen mode

Open database/migrations/timestamp_create_students_table.php file and paste

public function up()
{
    Schema::create('students', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->string('username');
        $table->string('phone');
        $table->string('dob');
        $table->timestamps();
    });
}
Enter fullscreen mode Exit fullscreen mode

Open app/Models/Student.php and paste in the $fillable array.

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
    use HasFactory;
    protected $fillable = [
        'name',
        'email',
        'username',
        'phone',
        'dob',
    ];    
}
Enter fullscreen mode Exit fullscreen mode

Run migration

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

We can't have a datatable without data right? So lets' create it!

Insert Dummy Data or Records

Open the database/seeds/DatabaseSeeder.php file and add the following code

<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;
class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker::create();
        $gender = $faker->randomElement(['male', 'female']);
        foreach (range(1,200) as $index) {
            DB::table('students')->insert([
                'name' => $faker->name($gender),
                'email' => $faker->email,
                'username' => $faker->username,
                'phone' => $faker->phoneNumber,
                'dob' => $faker->date($format = 'Y-m-d', $max = 'now')
            ]);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Run the following command to generate dummy data:

php artisan db:seed
Enter fullscreen mode Exit fullscreen mode

Now you will have data that looks something like this!

Image description

Easy right? 2 Steps all just for the setup! 3 Easy steps left for the actual datatable lol!

Image description

Step 3: Create DataTable Controller

Create a controller using the below command

php artisan make:controller StudentController
Enter fullscreen mode Exit fullscreen mode

Open app/Http/Controllers/StudentController.php file and add the following code

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Student;
use DataTables;
class StudentController extends Controller
{
    public function index()
    {
        return view('welcome');
    }

    public function getStudents(Request $request)
    {
        if ($request->ajax()) {
            $data = Student::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);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Define Route

Open routes/web.php and add the given code

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\StudentController;

Route::get('students', [StudentController::class, 'index']);
Route::get('students/list', [StudentController::class, 'getStudents'])->name('students.list');
Enter fullscreen mode Exit fullscreen mode

Step 5: Create the View and Display Data inside the DataTable

Open resources/views/welcome.blade.php file and place the following code.

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 8|7 Datatables Tutorial</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">
    <h2 class="mb-4">Laravel 7|8 Yajra Datatables Example</h2>
    <table class="table table-bordered yajra-datatable">
        <thead>
            <tr>
                <th>No</th>
                <th>Name</th>
                <th>Email</th>
                <th>Username</th>
                <th>Phone</th>
                <th>DOB</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('students.list') }}",
        columns: [
            {data: 'DT_RowIndex', name: 'DT_RowIndex'},
            {data: 'name', name: 'name'},
            {data: 'email', name: 'email'},
            {data: 'username', name: 'username'},
            {data: 'phone', name: 'phone'},
            {data: 'dob', name: 'dob'},
            {
                data: 'action', 
                name: 'action', 
                orderable: true, 
                searchable: true
            },
        ]
    });

  });
</script>
</html>
Enter fullscreen mode Exit fullscreen mode

The DataTable() method is defined, and the AJAX request is fetching the data from the server and displaying the name, email, user name, phone number and date of birth with the help of Yajra DataTable package.

We have also set orderable and searchable properties to true, so that you can search the data smoothly and make your programming tasks prosperous.

Now lets check it!

Run the following command and check our progress on the browser.

php artisan serve
Enter fullscreen mode Exit fullscreen mode

This is what it should look like!

Image description

Hurray! We did it and in just 5 Easy and Quick Steps!

Image description

Here are some related links to help you understand more about DataTables and Yajra:

Image description

Tips on how to improve your DataTables!

There are several ways in which you can speed up DataTables.

Tip #1 Enable Paging

$('#example').dataTable( {
    "paging": true
} );
Enter fullscreen mode Exit fullscreen mode

Tip #2 Disable OrderClasses

$('#example').dataTable( {
  "orderClasses": false
} );
Enter fullscreen mode Exit fullscreen mode

Tip #3 Enable DeferRender

$('#example').dataTable( {
  "ajax": "sources/arrays.txt",
  "deferRender": true
} );
Enter fullscreen mode Exit fullscreen mode

Tip #4 Enaber ServerSide

$('#example').dataTable( {
  "serverSide": true,
  "ajax": "xhr.php"
} );
Enter fullscreen mode Exit fullscreen mode

Tip #5 Lighten the load on your query!

Instead of getting all the columns and relationships on your query which can lead to a long time of loading, simplify your query by getting only the necessary columns and data you need before passing it on the client-side.

You can read more about it here

Top comments (1)

Collapse
 
jstnrme8 profile image
Justine Rome

Do you have tutorial on how to make Action buttons work?