Yajra DataTable is a popular package in Laravel. It allows you to create and display dynamic tables with server-side processing, pagination, and sorting capabilities. Also, it provides a fluent API that allows you to define your tables and their columns, and specify your data source. You can configure pagination, sorting, and filtering options. Yajra DataTables provides server-side processing. This allows you to work with large datasets without compromising performance. The server-side rendering reduces the load on your application and improves the user experience. Today, in this post, we will implement Yajra Datatable in Laravel 10 with server-side processing. Yajra DataTables can be integrated with Laravel’s Eloquent ORM, making it easy to work with your database data.
We are going to implement the below result in this example.
Hence, let’s quickly move to the example for implementing Yajra Datatable with server side.
Prerequisites
This example will be implemented in Laravel 10. Hence, to proceed with this, your system must meet the requirements as follows.
- PHP >=8.1
- Composer
- Apache/Nginx Server
- VS Code Editor (Optional)
- MySQL (version > 5)
Step 1 – Create a Project For Yajra Datatable in Laravel 10
In this step, you will need to create a Laravel 10 application. However, if you have already this then you can skip this step.
composer create-project --prefer-dist laravel/laravel my-app
Once you are done with the project setup then in the next step, you will require a database.
How to Create Dummy Data Using Tinker Factory in Laravel 10
Step 2 – Database Configuration in Laravel 10
Initially, you will need a MySQL database. Then you need to configure this with the Laravel 10 application. Hence, you have to navigate to the .env file and configure it under the DB section.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE={{ DATABASE_NAME }}
DB_USERNAME={{ DATABASE_USERNAME }}
DB_PASSWORD={{ DATABASE_PASSWORD }}
Next, you need to install the Yajra Datatable in Laravel 10.
How to Create a Seeder in Laravel 10 For Seeding Test Data
Step 3 – Install Yajra Datatable Package in Laravel 10
For installing the Yajra datatable in Laravel 10, you need to use the below command.
composer require yajra/laravel-datatables-oracle
The command will install the package of Yajra datatable in Laravel 10.
After installing the package, you need to configure a few things. Hence, let’s do that quickly.
How to Create Authentication Using Breeze Auth in Laravel 10
Add Providers and Alias For Yajra DataTable in Laravel 10
In order to use the Yajra Datatable in Laravel, you will have to register the provider class. Let’s start with adding the provider.
Simply, navigate to the config/app.php file in your project folder. There you will see the providers array. So, you have to add the below line in the array at the end of the default providers.
Yajra\DataTables\DataTablesServiceProvider::class,
After adding the provider, it will look like this.
Similarly, you will need to add its alias in the alias array just below the providers. However, this is not necessary, you can use this facade directly in your controller class. This is just for simplification.
'DataTables' => Yajra\DataTables\Facades\DataTables::class,
After adding this, the alias array will become like this.
You are done with the configuration. Now, let’s move to the functionality part.
Step 4 – Create a Model, Migration and Controller in Laravel 10
You need to have a model and a migration in order to go with the dynamic data. Hence, let’s create these files. You can create a controller together all in one as well.
php artisan make:model Employee -mc
The command will create a Model, migration and a controller. However, you can create factory, seeder, etc as well within a single command. But, it’s fine for now.
After having the migration, let’s add the schema over there.
<?php
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('employees', function (Blueprint $table) {
$table->id();
$table->string('first_name')->nullable();
$table->string('last_name')->nullable();
$table->string('gender')->nullable();
$table->string('email')->nullable();
$table->string('phone_number')->nullable();
$table->string('password')->nullable();
$table->string('address')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('employees');
}
};
Next, you need to migrate the above schema into the database.
How to Create Auth Scaffolding Using React JS in Laravel 10
Step 5 – Migrate the Table Schema
In order to migrate the schema, you have to run the below artisan command.
php artisan migrate
Also, you need to put fillable property inside the created model as shown below.
Step 6 – Add Fillable Propery in Model in Laravel 10
As per the schema, you have to add the mass assignment in the model.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
use HasFactory;
protected $fillable = [
'first_name',
'last_name',
'gender',
'email',
'phone_number',
'password',
'address'
];
}
After that we will be adding some dummy data for populating in the table. We will be applying DataTable with that table having data.
Step 7 – Create Factory in Laravel 10 For Dummy Data
For adding the dummy data for the testing purpose, we will be using the Factory class. You can create the factory class using the artisan command as shown below.
php artisan make:factory EmployeeFactory --model=Employee
Here, we have the model for which we will be creating the factory class.
After having the factory class, a definition of columns is needed.
Step 8 – Add Column Definition in Factory
The factory class needs to be specified the definition for which you want to insert the dummy data. Therefore, you have to navigate to the factory class and add the definition as per the schema of the table.
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Employee>
*/
class EmployeeFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'first_name' => fake()->firstName(),
'last_name' => fake()->lastName(),
'gender' => fake()->randomElement(['Male', 'Female']),
'email' => fake()->unique()->safeEmail(),
'phone_number' => $this->faker->phoneNumber(),
'password' => bcrypt('password'),
'address' => fake()->address(),
];
}
}
After adding the definition, you have to load the default dependencies with the application.
composer dump-autoload
Then you need to run the factory using Tinker.
Step 9 – Run Factory Class in Laravel 10 Using Tinker
Tinker is a command line interactive tool which is included in Laravel. You can create N number of test records using the Tinker in Laravel 10.
php artisan tinker
Employee::factory()->count(100)->create()
You can specify the number of records which will gonna insert. In the current scenario, the command will create 100 records as shown below.
After this step, you have to populate the data into the table.
Step 10 – Create Functionality to Implement Datatable
At the intial step of functionality, you will have to move to the controller. Then add the below functionality.
<?php
namespace App\Http\Controllers;
use App\Models\Employee;
use Illuminate\Http\Request;
use DataTables;
class EmployeeController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index(Request $request)
{
if ($request->ajax()) {
$data = Employee::all();
return DataTables::of($data)
->addIndexColumn()
->addColumn('action', function ($row) {
$btn = '<a href="javascript:void(0)" class="btn btn-primary btn-sm">View</a>';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
return view('employee');
}
}
After adding the functionality, you have to add the route respective to the function.
Step 11 – Add Routes in Laravel 10
To add the routes, simply navigate to the web.php file and add the below route.
<?php
use App\Http\Controllers\EmployeeController;
use Illuminate\Support\Facades\Route;
Route::get('employees', [EmployeeController::class, 'index'])->name('employees');
At last, you have to create a blade file for rendering the data.
Step 12 – Create a View in Laravel 10 For Rendering Data
Create a view with the name employee.blade.php inside the views folder. After that paste the below snippet inside it.
<!doctype html>
<html lang="en">
<head>
<title>Laravel 10 - Yajra Datatable with Server Side</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-fluid mt-5">
<h3 class="text-center font-weight-bold">Yajra Datatables in Laravel 10 </h3>
<table class="table mt-4" id="employees-table">
<thead>
<th> # </th>
<th> First Name </th>
<th> Last Name </th>
<th> Gender </th>
<th> Email </th>
<th> Phone </th>
<th> Address</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 = $('#employees-table').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('employees') }}",
columns: [{
data: 'DT_RowIndex',
name: 'DT_RowIndex'
},
{
data: 'first_name',
name: 'first_name'
},
{
data: 'last_name',
name: 'last_name'
},
{
data: 'gender',
name: 'gender'
},
{
data: 'email',
name: 'email'
},
{
data: 'phone_number',
name: 'phone_number'
},
{
data: 'address',
name: 'address'
},
{
data: 'action',
name: 'action',
orderable: false,
searchable: false,
}
]
});
});
</script>
</body>
</html>
That’s it. Now, you can run the application to test the result.
Vaibhav says
Hi Umesh,
Well you have provide a very good example yajra datatable. I have follow all the steps you have given and datable works properly. The only issue found is Search. The search functionality is not working, please see the video : https://app.screencast.com/nVnX1FjP2qFlX
Umesh Rana says
Hi Vaibhav,
Thanks for your valuable feedback and time to stay connected with us.
I have checked the recording, you will have to update the columns name as it is defined in the database in the JS as shown below.
columns: [{
data: 'DT_RowIndex',
name: 'DT_RowIndex'
},
{
data: 'first_name',
name: 'first_name'
},
{
data: 'last_name',
name: 'last_name'
},
{
data: 'gender',
name: 'gender'
},
{
data: 'email',
name: 'email'
},
{
data: 'phone_number',
name: 'phone_number'
},
{
data: 'address',
name: 'address'
},
{
data: 'action',
name: 'action',
orderable: false,
searchable: false,
}
]
Please update the name in this way and give a try. I have updated the code as well.