This content originally appeared on DEV Community and was authored by DEV Community
DataTables has two fundamental modes of operation:
Client-side processing - where filtering, paging and sorting calculations are all performed in the web-browser.
Server-side processing - where filtering, paging and sorting calculations are all performed by a server.
What does DataTables Server Side Rendering mean?
Imagine about the situation when you see thousands, hundreds of thousands or millions of records, and you have to scan through every record to get the required information.
Seems like difficult right? But not only that imagine the toll it would give to the browser, you're website will literally blackout.
Here comes Datatables which makes our work less miserable and offers
quick search
,pagination
,ordering
,sorting
functionalities to manage the data dynamically in the table.I will also give tips on how to improve the performance and speed of your Datatables at the end!
Lets start creating our DataTables!
Step 1: Create the Laravel App and Install Yajra DataTables
Run the below-mentioned artisan command to install a new laravel application.
composer create-project laravel/laravel laravel-yajra-datatables --prefer-dist
Then install the Yajra DataTable plugin in Laravel
composer require yajra/laravel-datatables-oracle
Go to config/app.php
file and paste this inside:
.....
.....
'providers' => [
....
....
Yajra\DataTables\DataTablesServiceProvider::class,
]
'aliases' => [
....
....
'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]
.....
.....
Run vendor publish command
php artisan vendor:publish --provider="Yajra\DataTables\DataTablesServiceProvider"
Easy right? Now that setups is done let's create our files!
Step 2: Create Model and Migrations
Run command to create a model
php artisan make:model Student -m
Open database/migrations/timestamp_create_students_table.php
file and paste
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 app/Models/Student.php
and paste in 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
php artisan migrate
We can't have a datatable without data right? So lets' create it!
Insert Dummy Data or Records
Open the database/seeds/DatabaseSeeder.php
file and add the following code
<?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')
]);
}
}
}
Run the following command to generate dummy data:
php artisan db:seed
Now you will have data that looks something like this!
Easy right? 2 Steps all just for the setup! 3 Easy steps left for the actual datatable lol!
Step 3: Create DataTable Controller
Create a controller using the below command
php artisan make:controller StudentController
Open app/Http/Controllers/StudentController.php
file and add the following code
<?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);
}
}
}
Step 4: Define Route
Open routes/web.php and add the given code
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\StudentController;
Route::get('students', [StudentController::class, 'index']);
Route::get('students/list', [StudentController::class, 'getStudents'])->name('students.list');
Step 5: Create the View and Display Data inside the DataTable
Open resources/views/welcome.blade.php
file and place the following code.
<!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>
The DataTable()
method is defined, and the AJAX request
is fetching the data from the server and displaying the name
, email
, user name
, phone number
and date of birth
with the help of Yajra DataTable package.
We have also set orderable
and searchable
properties to true, so that you can search the data smoothly and make your programming tasks prosperous.
Now lets check it!
Run the following command and check our progress on the browser.
php artisan serve
This is what it should look like!
Here are some related links to help you understand more about DataTables and Yajra:
-
Datatables in Laravel: Default and AJAX (Demo Project)
You will see here the 3 different types of handling DataTables:
- Laravel + HTML (Load Table on Page Load)
- Laravel + AJAX = DataTable (Client Side Rendering)
- Laravel + Yajra = DataTable (Server Side Rendering)
This content originally appeared on DEV Community and was authored by DEV Community
DEV Community | Sciencx (2022-02-25T12:07:49+00:00) Laravel 8 – DataTables Server Side Rendering (5 EASY STEPS). Retrieved from https://www.scien.cx/2022/02/25/laravel-8-datatables-server-side-rendering-5-easy-steps/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.