Laravel 8 - DataTables Server Side Rendering (5 easy steps) 💾📈📊
Tags: php, laravel, bestpractices, beginners
Published: 2022-02-25 12:07:49


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vdadalgqnmvj6rbehbg0.png)

**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`, `sorting`functionalities 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h3ro5z78tgff2lkshmo6.gif)

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

Then install the Yajra DataTable plugin in Laravel
```
composer require yajra/laravel-datatables-oracle
```

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

```
.....
.....
'providers' => [
	....
	....
	Yajra\DataTables\DataTablesServiceProvider::class,
]
'aliases' => [
	....
	....
	'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]
.....
.....
```

Run vendor publish command
```
php artisan vendor:publish --provider="Yajra\DataTables\DataTablesServiceProvider"
```

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

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();
    });
}
```

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',
    ];    
}
```

Run migration
```
php artisan migrate
```

> 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')
            ]);
        }
    }
}
```

Run the following command to generate dummy data:
```
php artisan db:seed
```

> Now you will have data that looks something like this!

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h5vnl8e19eiut4chhe1w.png)
 
> Easy right? 2 Steps all just for the setup! 3 Easy steps left for the actual datatable lol!

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/74zpbll7n3z4jxmoikzf.gif)

## Step 3: Create DataTable Controller

Create a controller using the below command
```
php artisan make:controller StudentController
```

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);
        }
    }
}
```



## 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');
```



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

> This is what it should look like!

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1ameo9r6gtnet3teuy3i.png)
 

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2iukb5hef5hr1ku4w2is.gif)

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

- [Datatables in Laravel: Default and AJAX (Demo Project)](https://www.youtube.com/watch?v=1wgLY-V69MM)
> You will see here the 3 different types of handling DataTables:
> 1. Laravel + HTML (Load Table on Page Load)
> 2. Laravel + AJAX = DataTable (Client Side Rendering)
> 3. Laravel + Yajra = DataTable (Server Side Rendering)

- [DataTables](https://datatables.net/)
- [Yajra Laravel DataTables Demo](https://datatables.yajrabox.com/)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f6dh2kmoqlccnnitszmu.gif)
 
## 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
} );
```

**Tip #2 Disable OrderClasses**
```
$('#example').dataTable( {
  "orderClasses": false
} );
```

**Tip #3 Enable DeferRender**
```
$('#example').dataTable( {
  "ajax": "sources/arrays.txt",
  "deferRender": true
} );
```
**Tip #4 Enaber ServerSide**
```
$('#example').dataTable( {
  "serverSide": true,
  "ajax": "xhr.php"
} );
```

**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](https://datatables.net/faqs/index#speed)