User data display is a fundamental necessity for web development. This tutorial's main goal is to show you how to use Yajra Datatables, a third-party package, to generate Datatables in Laravel.
This Laravel datatables tutorial demonstrates how to construct yajra datatables in Laravel while also teaching us the necessary techniques.
We will work to eliminate any ambiguity that may have surrounded your creation of the Laravel datatables example. We'll look at a laravel datatables AJAX example and a laravel Bootstrap datatable simultaneously.
Consider a scenario where you are presented with thousands of records and must manually search through each one to find the information you need. Doesn't seem easy, does it? To manage the data dynamically in the table, Datatables provides easy search, pagination, ordering, and sorting functions, in my opinion making our task less dreary.
A plug-in driven by jQuery, also known as the Javascript library, is called DataTables. It is a remarkably adaptable tool that adds all of these subtle and cutting-edge features to any static HTML table. It was created on the principles of progressive and dynamic augmentation.
Features
- Pagination
- Instant search
- Multi-column ordering
- Use almost any data source
- Easily theme-able
- Wide variety of extensions
- Mobile friendly
Even though we will only be using a few functionalities, such as search, sort, and pagination, we will attempt to integrate these elements with aesthetically pleasing HTML tables that are robust from a UI/UX standpoint.
Table of Contents
- Install Laravel App
- Install Yajra Datatables
- Set Up Model and Migrations
- Insert Dummy Data
- Create Controller
- Define Route
- Create View
Install Laravel App
In general, deploying a new Laravel application is the main emphasis of our initial step. Install the sacred canon by executing the artisan command listed below.
composer create-project laravel/laravel laravel-yajra-datatables --prefer-dist
cd laravel-yajra-datatables
Install Yajra Datatable Package
Yajra Datatables Library is a jQuery DataTables API for Laravel 4|5|6|7, and I wonder whether you've heard of it. By taking into account the Eloquent ORM, Fluent Query Builder, or Collection, this plugin manages the server-side operations of the DataTables jQuery plugin through the AJAX option.
The following command should theoretically assist you in installing the Yajra DataTable plugin in Laravel.
composer require yajra/laravel-datatables-oracle
Expand the basic functions of the package, such as the datatable service provider in the providers section and the alias inside the config/app.php file.
.....
.....
'providers' => [
....
....
Yajra\DataTables\DataTablesServiceProvider::class,
]
'aliases' => [
....
....
'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]
.....
.....
Continue by running the vendor publish command; this step is optional.
php artisan vendor:publish --provider="Yajra\DataTables\DataTablesServiceProvider"
Set Up Model and Migrations
Run a command to generate a model, which contains the database table's schema.
php artisan make:model Student -m
Add the following code to the file database/migrations/timestamp create students table.php.
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 the Student.php file in app/Models and add the schema to 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 using the following command.
php artisan migrate
Insert Dummy Data or Records
We need to create some dummy data in order to demonstrate Yajra DataTables in Laravel. By using the built-in plugin Faker, bogus data is correspondingly created in the database.
Add the following code to the database/seeds/DatabaseSeeder.php file.
<?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')
]);
}
}
}
To create fictitious data, execute the following command:
php artisan db:seed
Create DataTable Controller
Make a StudentController first, as it contains the essential logic for managing requests to retrieve data and show database entries.
Use the command listed below to create a controller.
php artisan make:controller StudentController
Add the following code to the file studentcontroller.php in app/Http/Controllers.
<?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);
}
}
}
Define Route
We must establish a route in this phase, which may deliver the datatables template into the display for our Laravel application.
Activate routes/web.php and insert the provided code.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\StudentController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('students', [StudentController::class, 'index']);
Route::get('students/list', [StudentController::class, 'getStudents'])->name('students.list');
Display Data with Yajra Datatables
Last but not least, we have arrived at the section of this Laravel Datatables Tutorial where we must improvise a welcome.blade.php file. It can be challenging to create a nice table if you are unfamiliar with HTML and CSS. This was the goal of bootstrap.
Place the following code in the welcome.blade.php file located in resources/views.
<!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>
Let me basically explain what I did above. With the aid of the Yajra DataTable package, the DataTable() method is defined, and the AJAX request is retrieving the data from the server and showing the name, email, user name, phone number, and date of birth.
Additionally, we have set the orderable and searchable characteristics to true so that you may successfully complete your programming chores by easily searching the data.
Run the ensuing command to check the browser for our progress.
php artisan serve
The following is the result of running the given command:
http://127.0.0.1:8000/students