Laravel datatable is a package to optimize the data by providing the features of sorting, paging, searching, etc. If you have thousands or millions of row containing the data then really it will be a slow process to load all the data. So, why don’t we try to load data in small chunks? This will optimize the view for rendering the data in a cleaved way. It will enhance the page loading speed by retrieving data by breaking down. So, this is possible by using Ajax. Ajax will load data asynchronously without refreshing the page. Therefore it will hit the request to the server and to manage this request, we will have to enable the server-side in the Laravel Datatable. So, let’s start by creating a new project in Laravel 7.
Prerequisites
For creating a Laravel 7 project, you will have the following tools with the required version.
- PHP >= 7.2.5
- MySQL > 5
- Apache/Nginx Server
- Composer
So, once you are ready, let’s create the project.
Laravel DataTable Server Side
Open the terminal or command prompt and then create a Laravel 7 project.
composer create-project --prefer-dist laravel/laravel yajra-datatable
The above command will start creating a new folder. Inside the folder, it will install the Laravel with the required packages.
How to Send Email Using Gmail SMTP in Laravel 7
Once the project has been created, let’s install the Yajra Datatable package inside the project.
Install Yajra DataTable in Laravel 7
Now, we will be installing the Yajra Datatable package in our project.
composer require yajra/laravel-datatables-oracle
It will take a couple of minutes to add the package. So, wait till it finishes.
After adding the package, you can verify the installation in the composer.json file. You can see the Yajra datatable package has been added.
How to Implement Google Charts in Laravel 7
Now, we will configure the database for our project.
Create and Configure Database in Laravel 7
Create a new database in MySQL. Either you can use MySQL command prompt or phpMyAdmin for creating the database.
CREATE DATABASE laravel_datatable;
After creating the database, we will configure our Laravel 7 project to sync with the database.
Laravel contains the environment file for such type of configuration. This file is present in root of the project with the name .env (environment). So, open the file and add the database credentials there that is showing below.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_datatable
DB_USERNAME={{-- DATABASE USERNAME -- }}
DB_PASSWORD={{-- DATABASE PASSWORD -- }}
Now, you are ready to go with the database.
In the next step, we will require a Model and migration for the tables. We will be managing the data dynamically from the database. So, let’s move on.
Create a Model and Migration
Laravel has a default model for the user. So, we can use this model or you can create a new one using the artisan command. In the project directory, we can find the model inside the app folder. The model name is User.php. The user migration file will be inside the database/migrations.
We will be adding some additional fields in the user migration file.
<?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('email')->unique();
$table->string('phone')->nullable();
$table->string('address')->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
After adding the fields, we will migrate the tables. So, that the tables will created in the database with the specified fields.
Migrate Database
For migrating the tables in the database, we will be using the below command.
php artisan migrate
The above command will generate the tables inside the database. So, now, we are ready with a database and table. Now, let’s proceed to implement the Yajra Datatable server side. Before implementing the datatable server side, we will require to have the data on which we will apply the Yajra datatable server side processing.
How to Use Http Client For Request Handling in Laravel 7
Add Mass Assignment in Model
What fields of the users table will be managed by the User model need to be specify. As we know, model syncs with the database for the sending and retrieving values. So, add the fillable data there as showing below.
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'phone', 'address'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
So, let’s create some dummy records for the users table. For creating the dummy records, we will be using the Laravel tinker factory class. This will generate the specified number of dummy data in each fields.
Laravel 7 Upload Multiple Images with Image Validation
Laravel Factory For Dummy Records
In the Laravel, factories contain the fields for which we are going to generate the dummy data. Default, there is one factory file for the user as UserFactory.php file.
<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\User;
use Faker\Generator as Faker;
use Illuminate\Support\Str;
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/
$factory->define(User::class, function (Faker $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'phone' => $faker->phoneNumber,
'address' => $faker->address,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi',
'remember_token' => Str::random(10),
];
});
After adding the fields inside the UserFactory let’s generate the records using the tinker class.
Create Dummy Records Using Tinker
Laravel provides the Tinker class for generating the number of specified records. Basically, this is connected with the Factory class. Factory class associated with the Model and the Model synced with the table inside the database.
php artisan tinker
factory (App\User::class, 200)->create()
It will take a couple of minutes to generate the dummy records.
How to Create a CRUD Application in Laravel 7
Create a Controller to Implement Datatable Server Side
In the next step, we will be implementing the Laravel yajra datatable server side for rendering the data in chunks. So, create a controller for the Users. Then we will add the functionality.
Now, we have the UserController.php, therefore, let’s add the functionality to fetch the records from the table. Then we’ll implement it into the datatable with the server side.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use DataTables;
class UserController extends Controller
{
public function index(Request $request) {
if ($request->ajax()) {
$data = User::select('*');
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){
$btn = '<a href="javascript:void(0)" class="edit btn btn-primary btn-sm">View</a>';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
return view('users-data');
}
}
For the above function call we will need to create a route. Then using the route we will be calling this function. So, let’s create a route.
Create a Route in Laravel 7
This route will be created inside the web.php. Hence, just add the below route.
Route::get('users', ['uses'=>'UserController@index', 'as'=>'users.index']);
Here, the route has been created. Now, for displaying the result in the datatable format, we will create a view.
Create a View For Yajra Datatable Server Side
In Laravel, you can create a view by creating a new blade file. Here, I have created a view with the name users-data.blade.php.
Inside the view add the below snippet to display the users record in the table format.
<!doctype html>
<html lang="en">
<head>
<title>Laravel 7 - Yajra Datatable Implementation</title>
<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://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-5">
<h3 class="text-center font-weight-bold">Yajra Datatable Server Side in Laravel 7 </h3>
<table class="table mt-4" id="usersTable">
<thead>
<th> # </th>
<th> Name </th>
<th> Email </th>
<th> Phone </th>
<th> Action </th>
</thead>
<tbody>
</tbody>
</table>
</div>
<script src="https://code.jquery.com/jquery-3.5.0.js" integrity="sha256-r/AaFHrszJtwpe+tHyNi/XCfMxYpbsRg2Uqn0x3s2zc=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var table = $('#usersTable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('users.index') }}",
columns: [
{data: 'id', name: 'id'},
{data: 'name', name: 'name'},
{data: 'email', name: 'email'},
{data: 'phone', name: 'phone'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
});
</script>
</body>
</html>
Now, the application is ready to serve. So, let’s see the result.
In the result, you will see the data has been loaded in chunks of 10 records on every click of pagination. It will make data retrieval fast than the normal load of data into the datatable.
Conclusion
The server side in the Laravel datatable has been implemented in this project. It will load the data very fast from the database. Actually, in every click of the pagination number the data will be loaded in small amount. So, the entire data will not be loaded at once. You can test it for the large number of records. In that case, you will analyze the loading time has been reduced. So, I hope this will be a real example for implementing the datatable server side.
Leave a Reply