For displaying large data sets in tabular form, you can use datatable in Laravel 9. You can use Yajra datatable in Laravel 9 using composer. It is a package available to install in your project. Once, it will be added, you can extend its functionalities. Basically, this works on the Ajax technique. It is very helpful when you have a large set of data. It loads data very quickly on the table in the form of chunks. So, let’s implement the functionality of Yajra datatable in Laravel 9.
So, in this post, we are going to achieve the above result. We will enable server-side processing. The server-side will process the large data set. It will render smoothly without delay.
Prerequisites
To proceed with the post, you will require the below configurations.
- PHP >=8.0.2
- Composer
- Apache/Nginx Server
- VS Code Editor (Optional)
- MySQL (version > 5)
Create Project For Yajra Datatable in Laravel 9
This step is not necessary if you already have a project setup. We will be using composer for creating the new project.
composer create-project --prefer-dist laravel/laravel yajra-datatable
After completing the installation, let’s configure a database for it.
How to Upload Multiple Images Using Ajax in Laravel 9
Create and Configure Database
For the database, open phpMyAdmin and create a new one. Now, come to the application and navigate to the .env file. Under the database section, replace the credentials as shown below.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=DATABASE_NAME
DB_USERNAME=DATABASE_USERNAME
DB_PASSWORD=DATABASE_PASSWORD
Once, it is done, let’s move to the next step.
How to Upload Image Using Ajax in Laravel 9 with Validation
Install Yajra Datatable Package in Laravel 9
For installing Yajra Datable, hit the below command in the terminal
composer require yajra/laravel-datatables-oracle
Once, it is installed, let’s add its providers and alias.
Add Providers and Alias For Yajra DataTables
You will have to navigate to the project configuration file. So, go to config/app.php. You will find the providers and aliases. So, add the below lines there.
Yajra\DataTables\DataTablesServiceProvider::class,
Similarly, add the alias for this as shown below.
'DataTables' => Yajra\DataTables\Facades\DataTables::class,
The next step is for migration and model. So, let’s proceed with it.
How to Create a CRUD Application Using Ajax in Laravel 9
Create a Model and Migration For Yajra Datatable in Laravel 9
Navigate to the project terminal and hit the below command.
php artisan make:model Post -m
It will create a model and a migration file for the Post. Now, let’s create the schema for the posts table.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title')->nullable();
$table->text('description')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
};
Now, let’s add the fillable property in the modal which is Post.php.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable = [
'title',
'description'
];
}
How to Upload Multiple Files in Laravel 9 with Validation
Create Factory Class For Adding Dummy Values
For populating data from a table, we need a few data. Hence, for feeding the data in the Posts table, I will use factory class. You can create the factory class for the posts table using the below command.
php artisan make:factory PostController
After creating the class, let’s add the below snippet in it.
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Post>
*/
class PostFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'title' => $this->faker->title(),
'description' => $this->faker->paragraph(),
];
}
}
How to Upload File in Laravel 9 With Validation
Interact Command Line Using Tinker
It will help to trigger the created factory definition. Open the terminal and hit the below command.
php artisan tinker
Post::factory()->count(400)->create()
The command will insert the specified count of posts in the posts table.
Create a Controller For Yajra Datatables in Laravel 9
For writing the functionality, create a controller using the below command.
php artisan make:controller PostController
Now, add the below snippet for rendering data on the view using Ajax request.
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
use DataTables;
class PostController extends Controller
{
/**
* Fetch Posts using Ajax
*
* @param Request $request
* @return void
*/
public function index(Request $request) {
if ($request->ajax()) {
$data = Post::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('posts');
}
}
Next, you have to create a route for this.
Create Route For Yajra Datatables in Laravel 9
<?php
use App\Http\Controllers\PostController;
use Illuminate\Support\Facades\Route;
Route::get("posts", [PostController::class, "index"])->name('posts');
The last step is for creating a view.
Upload Multiple Images in Laravel 9 with Validation
Create a View For Rendering Data Using Yajra Datatables
Inside the views folder, create a blade file named posts.blade.php. Now, you have to add the below snippet for having a table. This table will be extended by the datatable.
<!doctype html>
<html lang="en">
<head>
<title>Laravel 9 - 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 Datatables in Laravel 9 </h3>
<table class="table mt-4" id="posts-table">
<thead>
<th> # </th>
<th> Title </th>
<th> Description </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 = $('#posts-table').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('posts') }}",
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex'},
{data: 'title', name: 'title'},
{data: 'description', name: 'description'},
{data: 'action', name: 'action'}
]
});
});
</script>
</body>
</html>
Now, it’s done. You can run the application to see the result.
Conclusion
We created a large dataset using the factory class. Then we created a view with a Bootstrap table. Inside the table, we applied the datatables. Yajra datatable provided the filter, pagination, search, sorting features, etc.
Leave a Reply