How to Filter Datatable using Dropdown in Laravel 10

Websolutionstuff | Feb-07-2024 | Categories : Laravel PHP

Hello developers! 👋 Ever found yourself dealing with a DataTable in Laravel and wished for a nifty way to filter the data seamlessly? Well, you're in luck! In this step-by-step guide, I'm going to walk you through the process of filtering a DataTable using a dropdown in Laravel 10.

In this article, I'll give you step-by-step information about how to filter datatable using the dropdown in laravel 8, laravel 9, and laravel 10. 

So, let's see how to filter datatable using the dropdown in laravel 10, laravel 10 datatable filter using the dropdown, datatables filter dropdown, and datatable custom dropdown filter in laravel 8/9/10.

Step 1: Set Up a Laravel Project

If you haven't already, create a new Laravel project using Composer:

composer create-project --prefer-dist laravel/laravel your-project-name

 

Step 2: Set Up a Database

Configure your database connection in the .env file, and run migrations to create necessary tables:

php artisan migrate

 

Step 3: Create a Model

Generate a model for your data (e.g., Item):

php artisan make:model Item -m

This command will also create a migration file.

 

Step 4: Define the Model and Run Migrations

In the generated migration file (database/migrations/YYYY_MM_DD_create_items_table.php), define the columns for your DataTable. Then, run the migrations:

php artisan migrate

 

Step 5: Seed the Database (Optional)

If you want sample data, create a seeder for your model:

php artisan make:seeder ItemSeeder

Edit the seeder (database/seeders/ItemSeeder.php) and run:

php artisan db:seed --class=ItemSeeder

 

Step 6: Install DataTables

Install the DataTables package using Composer:

composer require yajra/laravel-datatables-oracle

 

Step 7: Set Up DataTables

In your controller, fetch the data and pass it to the DataTable. For example, in ItemController.php:

<?php

namespace App\Http\Controllers;

use App\Models\Item;
use Illuminate\Http\Request;
use DataTables;

class ItemController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = Item::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->where('name', 'LIKE', "%$search%")
                                ->orWhere('description', 'LIKE', "%$search%")
                                ->orWhere('price', 'LIKE', "%$search%");
                        });
                    }
                })
                ->rawColumns(['approved'])
                ->make(true);
        }

        return view('index');
    }
}

 

Step 8: Create a Blade View

Create a Blade view (e.g., resources/views/items/index.blade.php) and include the DataTable initialization script:

<html>
<head>
    <title>How to Filter Datatable using Dropdown in Laravel 10 - Websolutionstuff</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>How to Filter Datatable using Dropdown in Laravel 10 - Websolutionstuff</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>Description</th>
                <th>Price</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('items.index') }}",
          data: function (d) {
                d.approved = $('#approved').val(),
                d.search = $('input[type="search"]').val()
            }
        },
        columns: [
            {data: 'id', name: 'id'},
            {data: 'name', name: 'name'},
            {data: 'description', name: 'description'},
            {data: 'price', name: 'price'},
            {data: 'approved', name: 'approved'},
        ]
    });
  
    $('#approved').change(function(){
        table.draw();
    });
      
  });
</script>
</html>

 

Step 9: Create a Route

Define a route in web.php to load the view:

Route::get('/items', 'ItemController@index')->name('items.index');

 

Step 11: Run Your Laravel Development Server

Start the development server:

php artisan serve

 


You might also like:

Recommended Post
Featured Post
How To Get Hourly Data In MySQL
How To Get Hourly Data In MySQ...

In this tutorial, we will see how to get hourly data in mysql. Many times we need to get hourly data or we are required...

Read More

Feb-04-2022

How to Install Material Theme in Angular 17
How to Install Material Theme...

In this article, we'll install the material theme in angular 17. Material Theme brings a polished design and us...

Read More

Mar-29-2024

How To Install PHP XML Extension In Ubuntu
How To Install PHP XML Extensi...

In this article, I will guide you through the process of installing the PHP XML extension in Ubuntu. The PHP XML extensi...

Read More

Jul-19-2023

Send Mail Example In Laravel 8
Send Mail Example In Laravel 8

In this article, we will see send mail in laravel 8. here we will see how to send mail in laravel 8. Emai...

Read More

Oct-16-2020