Datatables Filter with Dropdown in Laravel 9 Example

Today, We are going to learn datatables filter with dropdown in Laravel 9 example. We’ll use custom Laravel dropdown filer. Datatables filter make its easer to display only those records which you select from dropdown.

In this tutorial you will learn advanced search filter using Dropdown in Laravel 9. So, Let get started with learning datatables filter with dropdown in Laravel 9 example.

Steps for Datatables Filter with Dropdown in Laravel 9 Example

  • Step 1: Installing a fresh new Laravel 9 Application
  • Step 2: Installing Yajra Datatable Package
  • Step 3: Creating Database and Migration
  • Step 4: Adding Dummy Records to User Table
  • Step 5: Creating Route
  • Step 6: Creating Controllers
  • Step 7: Creating Blade View
  • Step 8: Testing
  • Step 9: Conclusion

Also Read: Ajax File Upload with Progress Bar in Laravel 9 Example

Step 1: Installing a fresh new Laravel 9 Application

First step, Is to install a fresh new Laravel 9 Application. To install a Laravel application run the following command in terminal.

composer create-project --prefer-dist laravel/laravel dropdown-filter-app

cd dropdown-filter-app

Note : dropdown-filter-app” is our Laravel 9 application name.

Installing a fresh new Laravel 9 Application - Datatables Filter with Dropdown in Laravel 9 Example
Installing a fresh new Laravel 9 Application

Step 2: Installing Yajra Datatable Package

Now, We are going to install Yajra Datatable Composer Package. To install Yajra Datatable Composer Package run the following command in terminal.

composer require yajra/laravel-datatables-oracle

Add providers and alias too config/app.php

.....
'providers' => [
	....
	Yajra\DataTables\DataTablesServiceProvider::class,
]
'aliases' => [
	....
	'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]
.....
Installing Yajra Datatable Package - Datatables Filter with Dropdown in Laravel 9 Example
Installing Yajra Datatable Package

Step 3: Creating Database and Migration

Now, We are going to create database. Open phpmyadmin and create a new database as show in the below image.

Creating Database - Datatables Filter with Dropdown in Laravel 9 Example
Creating Database

Add the database details to .env file as show in the below image.

Database Configuration in .env file
Database Configuration in .env file

Now we are going to create migration file for add status column. To create a migration run the following command.

php artisan make:migration add_status_column

Also Read: How to Create RSS Feed in Laravel 9 Example

You can find the migration in database/migrations open the file and add the following code.

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->boolean('status')->default(0);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
};

Now run the migration by following command,

php artisan migrate
Run migration in artisan command
Run migration in artisan command

Step 4: Adding Dummy Records to User Table

Now, We are going to create some dummy records for the user table using thinker factory. To create a dummy records run the following command in terminal.

php artisan tinker

User::factory()->count(200)->create()
Adding Dummy Records to User Table
Adding Dummy Records to User Table

Step 5: Creating Route

So now, Adding route to our Laravel Application. Open routes/web.php and enter the following route to the file.

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\UserController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

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

Step 6: Creating Controllers

Now its time to create a UserController.php file inside app/Http/Controllers and enter the following code inside it.

<?php
       
namespace App\Http\Controllers;
      
use App\Models\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('status', function($row){
                         if($row->status){
                            return '<span class="btn btn-outline-success mb-0">Active</span>';
                         }else{
                            return '<span class="btn btn-outline-danger mb-0">Deactive</span>';
                         }
                    })
                    ->filter(function ($instance) use ($request) {
                        if ($request->get('status') == '0' || $request->get('status') == '1') {
                            $instance->where('status', $request->get('status'));
                        }
                        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(['status'])
                    ->make(true);
        }
        
        return view('users');
    }
}
Creating Controllers
Creating Controllers

Also Read: Create Ajax CRUD Laravel 9 Application Example

Step 7: Creating Blade View

Last step is to create Blade View File. Create a users.blade.php inside resources/views/ and enter the following code.

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Datatables Filter with Dropdown Example - LaravelTuts.com</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <!-- CSS only -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.12.1/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">

    <!-- JavaScript -->
    <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.12.1/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.12.1/js/dataTables.bootstrap5.min.js"></script>
</head>
<body>
    <div class="container">
        <div class="bg-dark p-4 text-center rounded-3 my-2">
            <h2 class="text-white m-0">Laravel Datatables Filter with Dropdown Example - LaravelTuts.com</h2>
        </div> 
        
        <div class="card my-2">
            <div class="card-body">
                <div class="form-group">
                    <label><strong>Status :</strong></label>
                    <select id='status' class="form-control" style="width: 200px">
                        <option value="">--Select Status--</option>
                        <option value="1">Active</option>
                        <option value="0">Deactive</option>
                    </select>
                </div>
            </div>
        </div>
    
        <table class="table table-bordered data-table my-2">
            <thead>
                <tr>
                    <th>No</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th width="100px">Status</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
     
    <script type="text/javascript">
        $(function () {
            var table = $('.data-table').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: "{{ route('users.index') }}",
                    data: function (d) {
                        d.status = $('#status').val(),
                        d.search = $('input[type="search"]').val()
                    }
                },
                columns: [
                    {data: 'id', name: 'id'},
                    {data: 'name', name: 'name'},
                    {data: 'email', name: 'email'},
                    {data: 'status', name: 'status'},
                ]
            });
            
            $('#status').change(function(){
                table.draw();
            });
        });
    </script>
</body>
</html>

Step 8: Testing

Now, Everything is done! We need to test our application. Start the Laravel application server by ruining the following command in terminal.

php artisan serve

So, Now you can open the following URL in any web browser.

http://127.0.0.1:8000/users

Preview:

Database Filter with Dropdown in Laravel 9 Example - Preview
Datatables Filter with Dropdown in Laravel 9 Example 8211 Preview

Step 9: Conclusion

Today, We had learn Datatables Filter with Dropdown in Laravel 9 Example. Hope this tutorial helped you with learning Laravel 9. If you have any question you can ask us at comment section below. If you like the tutorial please subscribe our YouTube Channel and follow us on social network Facebook and Instagram.

Also Read: How to get Country City Address from IP Address Laravel 9

3 Comments

Leave a Reply