Laravel provides the inbuilt package for the datatables that is called Yajra datatable. You can install it in your project by adding the composer command. This will enable the functionality of the datatable like sorting, ordering, searching, etc. In this tutorial, I will show you a quick guide to implement the datatable in Laravel 7 using the Yajra datatable. Laravel 7 Yajra datatable is easy to implement with few lines of code.
Prerequisites
To start in Laravel 7, you will have to configure your system with the required tools and versions.
- PHP >= 7.2.5
- MySQL > 5
- Apache/Nginx Server
- VS Code Editor (Optional)
- Composer
Create Laravel 7 Project For Yajra Datatable
We will create a project using the composer. So, let’s create a new project for implementing the Laravel 7 Yajra datatable. Open the terminal or command prompt and create a project.
composer create-project --prefer-dist laravel/laravel laravel7-yajra-datatable
The above command will create a new folder. Inside the project folder, the composer will add the necessary files and libraries. So, just wait while it will complete the entire setup.
How to Implement Google Charts in Laravel 7
Install Yajra DataTable in Laravel 7
Once, the project has created, navigate to the project folder by cd command. Now, we’ll be adding the datatable package inside the project.
composer require yajra/laravel-datatables-oracle
The command will install the data table dependencies inside the project. It will take a couple of minutes.
So, here the data table has been added to our project. You can check by navigating the composer.json file in the root of the project directory.
After adding the datatables package, we will have to register it inside the provider. Also, we will create an alias for the datatable.
Add Providers and Aliases For Yajra DataTable
You can find the provider and aliases inside the config/app.php. Here, you will have to register the provider and aliases. This will allow us to use the Yajra datatable anywhere in our project.
Yajra\DataTables\DataTablesServiceProvider::class,
'DataTables' => Yajra\DataTables\Facades\DataTables::class,
We can use alias directly instead of putting the entire namespace. Now, we will create a database. Then will connect the project with the database. So, let’s continue.
Laravel 7 RESTful APIs with Passport Authentication
Create and Configure Database
Open the MySQL database by opening phpMyAdmin or MySQL command line. Now, create a new database there. I have created a database using the below command.
create database laravel7_yajra_datatable;
The database has been created, now, let’s make a connection with the Laravel 7 project. Open the .env file that will be inside the root of the project.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel7_yajra_datatable
DB_USERNAME={{YOUR-DATABASE-USER}}
DB_PASSWORD={{YOUR-DATABASE-PASSWORD}}
Now, database has been configured. So, in the next step, will move to the model and migration.
Create a Model and Migration
Laravel provides a default model and migration for the Users. Hence, I am going to use this model and it’s migration file for the eloquent relation. You can create a new model whatever you want. In this post, I am just going to show you the implementation of datatable in Laravel 7. So, a single model and migration will be enough.
Navigate the directory database/migrations/create_users_table.php. Here, we will have the default fields for the users table that is associated with the User.php (Model).
<?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->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
In the above migration file, I have added few more fields. So that we can create a perfect data set.
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();
});
In the next step, we will be migrating the above schema into the table.
Migrate the Database
Once, you are done till the above steps, let’s migrate the database table. For migration, Laravel provides the command to migrate all the migration files inside the database. This will create the table(s) automatically. Also, inside the tables, the created fields will be mapped.
php artisan migrate
Here, the migrations are completed.
Find Nearest Location By Latitude and Longitude in Laravel 6
Add Mass Assignment in Model
I have added some fields inside the user migration file. That’s why I will have to add the fillable data inside the User.php (model).
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use 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',
];
}
Add Dummy Records Using Tinker
Laravel provides the feature to insert dummy records for testing purposes. For this feature, Laravel has the tinker package. This is an inbuilt feature in Laravel. The default model (User.php) is already connected with the factory class. Actually, the factory contains the fields for which we will be creating the dummy records. So, each fields will be specified here.
You can find by navigating the database/factories/UserFactory.php. Here, the file has the fields which are defined already. Now, we’ll add some more fields which will be inserting through the tinker class.
<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\User;
use Faker\Generator as Faker;
use Illuminate\Support\Str;
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/
$factory->define(User::class, function (Faker $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
});
We will need to create the tinker command to execute the process.
php artisan tinker
factory(App\User::class, 200)->create();
Here, I have executed the tinker factory command. Basically, it is connected with the User model. The tinker command will insert the values for which it is specified. So, here the User model is specified. It will take a couple of minutes to insert 200 records.
After inserting the dummy records, you can check the table. The SQL provides a query to count the number of rows inside the table.
select count(*) from users;
That’s it for the model, now, we will have to write the functionality to fetch the records from the table. So, let’s create a controller first.
Create a Controller
In Laravel, you can create the controller by using the artisan command. You don’t need to create any file manually. So, here we’ll create a controller for the User model that can easily control and manage the data.
php artisan make:controller UserController
Here, the controller has been created. Now, let’s put some functionality there.
Inside the controller add the below snippet. In this, snippet, I have used the Model, and the DataTables that is created in the alias.
Then in the getUsers() function, I have retrieved all the records from the users table and then returned it in the form of datatable columns. Finally, returned the views.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use DataTables;
class UserController extends Controller
{
public function getUsers(Request $request) {
if ($request->ajax()) {
$data = User::all();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row) {
$btn = '<a href="javascript:void(0)" class="edit btn btn-primary btn-sm">View</a>';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
return view('users');
}
}
Create a Route for the Controller
For the UserController, we will need a route because we have the single function. So, add the below route inside the routes/web.php fie.
Route::get("users", "UserController@getUsers");
Create a View For Yajra DataTable
For displaying the data inside the datatable, we will have to create a view. The view will load with the data and it will bind in the datatable to perform a certain action.
In Laravel, you can create a view by moving to the resources/views folder. Now, create a blade file. I have created a view named users.blade.php. Add the below snippet inside this file.
<!doctype html>
<html lang="en">
<head>
<title>Laravel 7 - 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 7 </h3>
<table class="table mt-4" id="usersTable">
<thead>
<th> # </th>
<th> Name </th>
<th> Email </th>
<th> Phone </th>
<th> Address </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', orderable: false, searchable: false},
]
});
});
</script>
</body>
</html>
Save and run the application to see the result.
php artisan serve
When your application will start, just open the URL http://localhost:8000/users
Conclusion
We have successfully implemented the Yajra DataTable in Laravel 7. Really, this is a cool feature in Laravel that is used to manage the large number of records in a single table. It provides the functionality to paginate the rows into chunks. Data sorting, searching, etc. are easy to manage. So, I hope, you will enjoy this post and this will help you to implement in your project. For any kind of help and query don’t forget to ask by doing comment below.
Leave a Reply