Laravel 8 Datatables Filter with Dropdown

Websolutionstuff | Jun-16-2021 | Categories : Laravel PHP

In this example we will see laravel 8 datatables filter with dropdown, Here we will add datatables custom filter using field and searching data without refresh datatable.

Using yajra datatable package you can directly listing of records with pagination, sorting as well as filter feature available but if you want to add advance filter like datatable dropdown or dropdown search filter in laravel datatables or yajra datatables filter column then you need to add below code step by step to integrate yajra datatable dropdown filter with laravel.

 

Step 1 : Install Laravel for laravel 8 datatables filter with dropdown tutorial

Step 2 : Integrate Yajra Datatable for Dropdown Filter 

Step 3 : Add New Column in Users Table for filter column

Step 4 : Add Record using Tinker

Step 5 : Add Route

Step 6 : Create Controller

Step 7 : Create BLade file for View

 

Step 1 : Install Laravel for laravel 8 datatables filter with dropdown tutorial

Here, I have install new laravel application for laravel 8 datatables filter with dropdown example.

composer create-project --prefer-dist laravel/laravel datatable-example

 

Step 2 : Integrate Yajra Datatable for Dropdown Filter 

Now, we need to install or Integrate Yajra Datatable for Dropdown Filter using composer command in your terminal.

composer require yajra/laravel-datatables-oracle

 

 

After installation of datatable we need to add providers and alias in config/app.php.

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

 

Step 3 : Add New Column in Users Table for filter column

After that we will add new column using migration 

php artisan make:migration add_approved_column

 

database/migrations/2021_16_06_043348_add_approved_column.php

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
class AddApprovedColumn extends Migration
{
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->boolean('approved')->default(0);
        });
    }
    public function down()
    {
         
    }
}

 

Run this migration.

php artisan migrate

 

Step 4 : Add Record using Tinker

We will add some recored to check our example using tinker.

 

php artisan tinker

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

 

Step 5 : Add Route

Now add route routes/web.php in this location.

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

 

 

Step 6 : Create Controller

 

<?php
       
namespace App\Http\Controllers;
      
use App\User;
use Illuminate\Http\Request;
use DataTables;
      
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = User::select('*');
            return Datatables::of($data)
                    ->addIndexColumn()
                    ->addColumn('approved', function($row){
                         if($row->approved){
                            return '<span class="badge badge-primary">Yes</span>';
                         }else{
                            return '<span class="badge badge-danger">No</span>';
                         }
                    })
                    ->filter(function ($instance) use ($request) {
                        if ($request->get('approved') == '0' || $request->get('approved') == '1') {
                            $instance->where('approved', $request->get('approved'));
                        }
                        if (!empty($request->get('search'))) {
                             $instance->where(function($w) use($request){
                                $search = $request->get('search');
                                $w->orWhere('name', 'LIKE', "%$search%")
                                ->orWhere('email', 'LIKE', "%$search%");
                            });
                        }
                    })
                    ->rawColumns(['approved'])
                    ->make(true);
        }
        
        return view('users');
    }
}

 

Step 7 : Create BLade file for View

 

<html>
<head>
    <title>Laravel 8 Datatables Filter with Dropdown - websolutionstuff.com</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.25/css/dataTables.bootstrap5.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.25/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.25/js/dataTables.bootstrap5.min.js"></script>

</head>
<body>
     
<div class="container">
    <h1>Laravel 8 Datatables Filter with Dropdown - websolutionstuff.com</h1>
      
    <div class="card">
        <div class="card-body">
            <div class="form-group">
                <label><strong>Approved :</strong></label>
                <select id='approved' class="form-control" style="width: 200px">
                    <option value="">Approved</option>
                    <option value="1">Yes</option>
                    <option value="0">No</option>
                </select>
            </div>
        </div>
    </div>
  
    <table class="table table-bordered data-table">
        <thead>
            <tr>
                <th>No</th>
                <th>Name</th>
                <th>Email</th>
                <th width="100px">Approved</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.approved = $('#approved').val(),
                d.search = $('input[type="search"]').val()
            }
        },
        columns: [
            {data: 'id', name: 'id'},
            {data: 'name', name: 'name'},
            {data: 'email', name: 'email'},
            {data: 'approved', name: 'approved'},
        ]
    });
  
    $('#approved').change(function(){
        table.draw();
    });
      
  });
</script>
</html>

 

Now, you need to run this application in your browser to see output.

 

Recommended Post
Featured Post
Laravel 9 Import Export CSV/EXCEL File Example
Laravel 9 Import Export CSV/EX...

In this tutorial, I will give you laravel 9 import export csv and excel file example. We will simply create import...

Read More

Feb-19-2022

Autocomplete Search from Database in Laravel 11
Autocomplete Search from Datab...

Hello, laravel web developers! In this article, we'll see how to autocomplete a search from a database in larav...

Read More

Jun-24-2024

Laravel 9 Livewire Dependent Dropdown
Laravel 9 Livewire Dependent D...

In this article, we will see the laravel 9 livewire dependent dropdown. Here, we will learn how to create a dependent dr...

Read More

Nov-29-2022

Laravel 9 Generate PDF File Using DomPDF
Laravel 9 Generate PDF File Us...

In this tutorial, we will see laravel 9 generate pdf file using dompdf. For generating pdf files we will use the la...

Read More

Feb-25-2022