For managing the large number of data set in a tabular form, you will require a Datatable in Laravel. Datatable provides an easy way to handle the data in the form of a table. You can apply the datatable to any table. After applying the table will have the options to search, filter, sort, pagination, etc. There are different plugins for the datatable. jQuery provides the Datatable library you can use this. But, for implementing datatable in Laravel we have a package called Yajra. The Yajra Datatables is an open-source package. You can find out it on Github. Today, in this post, I will implement Yajra datatable in Laravel 8. Hence, let’s begin by creating a new project.
Prerequisites
We will create this project in Laravel 8. So, you must have the below tools for the Laravel 8 development.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
Create Project For Datatable in Laravel 8
For creating a new project in Laravel 8, I will use the composer. So, to hit the command for creating the project, open the terminal.
composer create-project --prefer-dist laravel/laravel yajra-datatable
This will start creating the project in the specified directory. The Laravel installation will add all the required libraries and files. So, wait until the installation completes.
In the next step, we will add the Yajra Datatables package.
Add Yajra DataTables Package in Laravel 8
Laravel provides a package for implementing the datatables. This package is open source and available at the Github repository.
composer require yajra/laravel-datatables-oracle
Move inside the project folder and hit the above command in the terminal. It will add the yajra datatables package.
So, now, we have the datatable package installed. You can check it in the composer.json file.
In the next step, we will require to add a provider and alias for the Yajra Datatables. So, that we can include the namespace using this alias.
Add Providers and Alias For Yajra DataTables
You will have to move inside the project configuration file. So, go to config/app.php. You will find the providers and aliases. Hence, add the below lines there.
Yajra\DataTables\DataTablesServiceProvider::class,
'DataTables' => Yajra\DataTables\Facades\DataTables::class,
Now, you can use the Yajra Datatables namespace in any class. You will have to use it’s namespace alias.
In the next step, we will create a database. Then we will have to configure it for the Laravel 8 project.
Create and Configure Database
For creating the database, I will be using the MySQL command line. So, create a database there.
CREATE DATABASE laravel_datatable;
After creating the database, add it inside the .env file.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_datatable
DB_USERNAME=root
DB_PASSWORD=root
Now, we have added the database credentials in the project.
Create a Model and Migration
In this step, we will setup a model and the migration. As we already know, Laravel provides a default model and migration for the User. So, we can use these default files. Otherwise, you can create a new one.
So, I am going to use the default model and migration file of the User.
Firstly, add some fields in the create_users_table.php 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');
}
}
In this migration file, I have added two additional fields. One for the phone number and another for the address.
As per this migration, we will have to set the fillable data in the User model.
Add Fillable Data in User Model
We will have to define the fillable data field as per the migration file. So, I have added the fields.
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, 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',
];
}
Now, migrate the table in the database.
php artisan migrate
This command will migrate the tables in the database.
Now, the database tables are ready. So, we will add some dummy records in the user table.
Use Factory Class to Add Dummy Records
Before adding the dummy records for a table, we will have to set the fields. This factory class is associated with the model. And the model fill ups the data to the associated table. So, this works in this manner.
Laravel provides a default factory class for the user. This is as like the default model and migration of the user. You can create new one if you have another model and migration.
Here, I will be using this UserFactory. You can find the factory files inside the database/factories folder. So, add the fields as per the migration and fillable data of your table.
<?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,
'email' => $this->faker->unique()->safeEmail,
'phone' => $this->faker->phoneNumber,
'address' => $this->faker->address,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
}
}
Now, the factory is ready to insert the dummy records for the specified fields. For inserting the dummy records, we will have to hit the tinker command.
Insert Dummy Records Using Tinker
Laravel 8 has re-written the factory class. So, if you will try using the older commands then it won’t work. This is one of the new features in Laravel 8. Here, the factory is already defined in the model class.
Let’s take a look of the User model. Here, you will see in the namespace the HasFactory class is included. In the model class it is used to run the factory directly through the model.
You can write the tinker command as showing below.
php artisan tinker
User::factory()->count(200)->create()
After running the above command, it will start creating the specified number of records.
In the next step, we will have to create a controller. The controller will fetch the data from the table using the eloquent.
Create a Controller For Datatable in Laravel 8
We will create a controller for the user. So, that we can fetch the data and return to the view.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use DataTables;
class UserController extends Controller
{
public function users(Request $request) {
if ($request->ajax()) {
$data = User::all();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row) {
$action_btn = '<a href="javascript:void(0)" class="btn btn-primary btn-sm">View</a>';
return $action_btn;
})
->rawColumns(['action'])
->make(true);
}
return view('users');
}
}
In the above function, I have accepted the ajax request. This ajax request will come from the view. Then retrieved the data from the Users table using the eloquent. At last, passed the data into the Yajra datatables and returned to view for rendering.
Create a Route
For the above function, I will create a route in the web.php file.
<?php
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
Route::get("users", [UserController::class, "users"]);
Create a View
For displaying the users data, we will require to create a view. And from this view, the ajax request will be triggered to the controller. This ajax request will fetch the users data asynchronously.
I have created a view named users.blade.php. Add the below snippet in the blade file.
<!doctype html>
<html lang="en">
<head>
<title>Laravel 8 - 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 Implementation in Laravel 8 </h3>
<table class="table mt-4" id="usersTable">
<thead>
<th> # </th>
<th> Name </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 = $('#usersTable').DataTable({
// processing: true,
serverSide: true,
ajax: "{{ url('users') }}",
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex'},
{data: 'name', name: 'name'},
{data: 'email', name: 'email'},
{data: 'phone', name: 'phone'},
{data: 'address', name: 'address'},
{data: 'action', name: 'action'}
]
});
});
</script>
</body>
</html>
Now, application is ready to run. So, let’s check the result.
Yeah, it is working and we have all the functionality enabled. Like searching, ordering etc.
Conclusion
We have implemented the Yajra datatables in Laravel 8. Yajra datatable provides an easy approach to manage the large number of data. Here, we have created the dummy records in Laravel using the factory and tinker. You can specify the number of records to create. We fetched the data from the table using the eloquent model. Then the data is binded into the datatable and returned to the view. This formed a tabular representation of the data. So, I hope guys, you will find it helpful.
jairo says
Thank you sir.
It is an amazing presentation. I love the details of every step and what it is important is that it works
Thank you again