Welcome to our step-by-step guide on implementing Yajra DataTables in a Laravel 10 project. Yajra DataTables is a powerful library that seamlessly integrates the jQuery DataTables API with Laravel. It simplifies server-side operations using AJAX and supports Eloquent ORM, Fluent Query Builder, or Collection.
Follow along as we set up a Laravel project, install Yajra Datatables, create a model and migrations, generate dummy records, set up a controller, define routes, and finally, display records with a visually stunning table using Bootstrap.
Step 1: Install the Laravel App
Let’s start by creating a new Laravel project using Composer:
composer create-project laravel/laravel laravel-yajra-datatables --prefer-dist
cd laravel-yajra-datatables
Step 2: Install Yajra Datatable Package
Next, we’ll install the Yajra DataTable plugin:
composer require yajra/laravel-datatables-oracle
After installing, expand the foundational service by adding the service provider and alias in the config/app.php
file:
// config/app.php
'providers' => [
// ...
Yajra\DataTables\DataTablesServiceProvider::class,
],
'aliases' => [
// ...
'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]
Run the vendor publish command:
php artisan vendor:publish --provider="Yajra\DataTables\DataTablesServiceProvider"
Step 3: Set Up the Model and Migrations
Generate a model and migration for the ‘blogs’ table:
php artisan make:model Blog --m
Add the following code to the generated migration file:
// database/migrations/xxxx_xx_xx_create_blogs_table.php
public function up(): void
{
Schema::create('blogs', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('description');
$table->text('content');
$table->timestamps();
});
}
In the app/Models/Blog.php
file, add the following code:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Blog extends Model
{
use HasFactory;
protected $fillable = [
'title',
'description',
'content',
];
}
Run the migration command:
php artisan migrate
Step 4: Generate Dummy Records
To test Yajra Datatables, let’s create dummy records using Faker. Open database/seeders/DatabaseSeeder.php
and add the following code:
// database/seeders/DatabaseSeeder.php
public function run(): void
{
$faker = \Faker\Factory::create();
for ($i = 0; $i < 200; $i++) {
\DB::table('blogs')->insert([
'title' => $faker->sentence($nbWords = 6,
$variableNbWords = true),
'description' => $faker->paragraph
($nbSentences = 2,
$variableNbSentences = true),
'content' => $faker->text($maxNbChars = 500),
]);
}
}
Run the seeder command:
php artisan db:seed
Step 5: Create a Controller
Now, let’s create a controller for our Blog model:
php artisan make:controller BlogController
Open the file app/Http/Controllers/BlogController.php
and add the following code:
<?php
namespace App\Http\Controllers;
use Yajra\DataTables\Facades\Datatables;
use App\Models\Blog;
use Illuminate\Http\Request;
class BlogController extends Controller
{
public function index(Request $request)
{
if ($request->ajax()) {
$data = Blog::all();
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);
}
return view('welcome');
}
}
Step 6: Create Routes
Create routes to display the data table in our view. Open routes/web.php
and add the following code:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BlogController;
Route::get('blogs', [BlogController::class, 'index'])->name('blogs.index');
Step 7: Displaying Records with Laravel Yajra Datatables
Create the welcome.blade.php
file in resources/views/
and place the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Implementing Yajra Datatables in Laravel 10</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.11.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.5.1.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.11.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://cdn.datatables.net/1.11.4/js/dataTables.bootstrap5.min.js"></script>
</head>
<body>
<div class="container">
<h1>Implementing Yajra Datatables in Laravel 10</h1>
<table class="table table-bordered data-table">
<thead>
<tr>
<th>No</th>
<th>Title</th>
<th>Description</th>
<th>Content</th>
<th width="105px">Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script type="text/javascript">
$(function() {
gb_DataTable = $(".data-table").DataTable({
autoWidth: false,
order: [0, "ASC"],
processing: true,
serverSide: true,
searchDelay: 2000,
paging: true,
ajax: "{{ route('blogs.index') }}",
iDisplayLength: "25",
columns: [
{ data: 'id', name: 'id' },
{ data: 'title', name: 'title' },
{ data: 'description', name: 'description' },
{ data: 'content', name: 'content' },
{ data: 'action', name: 'action', orderable: false, searchable: false },
],
lengthMenu: [25, 50, 100]
});
});
</script>
</body>
</html>
Finally, run the following command and view the result in your browser:
php artisan serve
Visit http://<hostname>:<port>/ to see the Yajra Datatables in action!