Laravel Datatables stands out as a widely embraced package, offering a straightforward and efficient approach to integrate server-side processing for data tables. With its user-friendly features, such as column filtering and sorting, this package simplifies the customization of data tables. This tutorial is designed to guide you through the process of implementing custom filtering and searching in Laravel Datatables, utilizing the Yajra package. Accompanied by step-by-step instructions, code snippets, and a functional demo, we will explore how to enhance your Laravel application’s data presentation.

Prerequisites

Before diving into this tutorial, ensure that you have the following prerequisites installed:

Once you have installed the packages, you are now ready to start developing custom filtering using datatable. Follow the upcoming steps to the start the development.

Step 1: Creation of Model

To proceed, our initial step involves the creation of a model specifically tailored for our data table. To illustrate this process, we will generate a straightforward User model as an example.

<?php


namespace App\Models;


use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;


class User extends Model
{
   protected $fillable = [
       'name',
       'email',
   ];
}

Step 2: Initiating the Migration

After creating the user model, the next step involves initiating a migration to set up the database table for user data. This ensures a smooth integration of the model into the database, providing an organized storage system for user information.

<?php


use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;


class CreateUsersTable extends Migration
{
   public function up()
   {
       Schema::create('users', function (Blueprint $table) {
           $table->id();
           $table->string('name');
           $table->string('email')->unique();
           $table->timestamps();
       });
   }


   public function down()
   {
       Schema::dropIfExists('users');
   }
}

Now run the following command to migrate this file:

php artisan migrate

Step 3: Create a Seeder

Now, we proceed to create a seeder to populate the database with dummy data, essential for testing and validating system functionality.

<?php


use Illuminate\Database\Seeder;
use App\Models\User;


class UsersTableSeeder extends Seeder
{
   public function run()
   {
       User::factory()->count(100)->create();
   }
}

During this phase, it is imperative to incorporate the seeder file into the designated location, specifically within the seeders/DatabaseSeeder.php file. This ensures the seamless integration of the seeder into the overall database seeding process, thereby enhancing the efficiency of populating the database with the predefined dummy data.

<?php


namespace Database\Seeders;


use Illuminate\Database\Seeder;


class DatabaseSeeder extends Seeder
{
   public function run()
   {
       $this->call([ UsersTableSeeder::class ]);
   }
}

After incorporating the seeder file, execute the seeder command to populate the database with dummy data, facilitating a robust evaluation of system functionality.

php artisan db:seed

Step 4: Add Package

To integrate the yajra/laravel-datatables-oracle package into our project seamlessly, we can execute the specified command to ensure the proper inclusion and utilization of this package within our Laravel environment.

composer require yajra/laravel-datatables-oracle

Step 5: Package Register

Upon successful installation of the package, it becomes imperative to proceed with the registration of the service provider and alias within the configuration file, config/app.php , ensuring the proper configuration and utilization of the package functionalities within the Laravel project.

 'providers' => [
      ...
   Yajra\DataTables\DataTablesServiceProvider::class,
  ],

  'aliases' => [
      ...
  'DataTables' => Yajra\DataTables\Facades\DataTables::class,
  ],

Step 6: Create Dummy Records

In this step, we will create some dummy users using Tinker factory. so let’s create dummy records using the bellow command: (Note: if you follow step 3 then ignore it)

php artisan tinker

factory(App\User::class, 200)->create();

Step 7: Create Route

In this step we need to create a route for data tables layout file and another one for getting data. so open your routes/web.php file and add the following route:

Route::get('users', ['uses'=>'UserController@index', 'as'=>'users.index']);

Step 8: Create Controller

As the next step in the process, it is essential to create a new controller, designated as UserController , which will serve as a pivotal component in managing and orchestrating the various actions and functionalities associated with user-related operations within the application.

php artisan make:controller UserController

Step 9: Create Controller File

In this  step, now we should create a UserController file. This controller will manage the layout and get data requests and return responses, so put below content in the controller file:

<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use DataTables;
use Illuminate\Support\Str;
class UserController extends Controller{


   public function index(Request $request)
   {
       if ($request->ajax()) {
           $data = User::latest()->get();
           return Datatables::of($data)
               ->addIndexColumn()
               ->filter(function ($instance) use ($request) {
                   if (!empty($request->get('email'))) {
                       $instance->collection = $instance->collection->filter(function ($row) use ($request) {
                           return Str::contains($row['email'], $request->get('email')) ? true : false;
                       });
                   }
                   if (!empty($request->get('search'))) {
                       $instance->collection = $instance->collection->filter(function ($row) use ($request) {
                           if (Str::contains(Str::lower($row['email']), Str::lower($request->get('search')))){
                               return true;
                           }else if (Str::contains(Str::lower($row['name']), Str::lower($request->get('search')))) {
                               return true;
                           }
                           return false;
                       });
                   }
               })
               ->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');
   }
}

Step 10: Create View

In Last step, let’s create users.blade.php(resources/views/users.blade.php) for layout and we will write design code here and put following code:

<!DOCTYPE html>
<html>
<head>
   <title>Custom filter/Search with Laravel Datatables Example</title>
   <meta name="csrf-token" content="{{ csrf_token() }}">
   <link rel="stylesheet"     href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
   <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">
   <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.16/js/jquery.dataTables.min.js"></script>
   <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
   <script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
</head>
<body>
<div class="container">
   <h1>Custom filter/Search with Laravel Datatables Example</h1>
   <input type="text" name="email" class="form-control searchEmail" placeholder="Search for Email Only...">
   <br>
   <table class="table table-bordered data-table">
       <thead>
       <tr>
           <th>No</th>
           <th>Name</th>
           <th>Email</th>
           <th width="100px">Action</th>
       </tr>
       </thead>
       <tbody>
       </tbody>
   </table>
</div>
</body>
<script type="text/javascript">
   $(function () {
       var table = $('.data-table').DataTable({
           processing: true,
           serverSide: true,
           ajax: {
               url: "{{ route('users.index') }}",
               data: function (d) {
                   d.email = $('.searchEmail').val(),
                       d.search = $('input[type="search"]').val()
               }
           },
           columns: [
               {data: 'DT_RowIndex', name: 'DT_RowIndex'},
               {data: 'name', name: 'name'},
               {data: 'email', name: 'email'},
               {data: 'action', name: 'action', orderable: false, searchable: false},
           ]
       });
       $(".searchEmail").keyup(function(){
           table.draw();
       });
   });
</script>
</html>

Step 11: Run Project

With all the necessary configurations in place, we are now prepared to execute our example. To initiate a quick run, enter the specified command and observe the output for a seamless and efficient demonstration of the example:

php artisan serve

Step 12: View In Browser

Following the completion of the previous steps, you are now able to access the URL provided below via your preferred web browser. This allows you to view and interact with the corresponding content or application being served:

http://localhost:8000/users

Conclusion

In conclusion, this tutorial serves as a comprehensive guide for implementing custom filtering and searching in Laravel Datatables, leveraging the powerful features offered by the Yajra package. By following the step-by-step instructions, integrating code snippets, and exploring a functional demo, you can enhance your Laravel application’s data presentation with ease. With the simplified approach provided, users can efficiently manage and manipulate data tables, ultimately improving the user experience and functionality of their Laravel projects.

This page was last edited on 11 March 2024, at 11:13 am