Datatable Filter With Dropdown In Laravel 9

In this article, we will see a datatable filter with a dropdown in laravel 9. Here we will add data tables with custom filters using fields and searching data without refreshing datatable. we will see the datatable custom dropdown filter on the server-side example.

So, let's see the dropdown filter in laravel 9, laravel 9 custom datatable filter, and the datatable custom filter dropdown server side.

Using yajra datatable package you can directly list records with pagination, sorting as well as filter features available but if you want to add an advanced filter like the 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 9.

Step 1: Install Laravel 9 for Custom Filter with Dropdown

Step 2: Install Yajra Datatable 

Step 3: Add New Column In Users Table

Step 4: Add Record using Tinker

Step 5: Add Routes

Step 6: Create Controller

Step 7: Create Blade file for View

 

Step 1: Install Laravel 9 for Custom Filter with Dropdown

In this step, we will install a new laravel 9 application using the below command.

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

 

 

Step 2: Install Yajra Datatable 

Now, we will install or integrate yajra datatable using the composer command in your terminal.

composer require yajra/laravel-datatables-oracle

This step is optional if you are using Laravel 5.5+. Open the file config/app.php and then add the following service provider.

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

After completing the above step, use the following command to publish the configuration & assets.

php artisan vendor:publish --tag=datatables

 

Step 3: Add New Column in Users Table

Now, we will add a new column in the user table using the migration command.

php artisan make:migration add_approved_column

In the database/migrations/ file path you can find the add_approved_column.php file. And add the below code in that file.

<?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()
    {
         
    }
}

After changes in the migration file run the below command in your terminal.

php artisan migrate

 

 

Step 4: Add Record using Tinker

In this step, we will create dummy records to check our example using tinker.

php artisan tinker

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

 

Step 5: Add Routes

Now, add a route in the routes/web.php file.

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

 

Step 6: Create Controller

In this step, we will add the below code in the controller file.

<?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

Now, create a blade file and add datatable with a dropdown like the below code.

<html>
<head>
    <title>Datatable Filter With Dropdown In Laravel 9 - Techsolutionstuff</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>Datatable Filter With Dropdown In Laravel 9 - Techsolutionstuff</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>

 


You might also like:

RECOMMENDED POSTS

FEATURE POSTS