In the Last tutorial, we have seen single select option product filter in Laravel 10. But in this tutorial, we will see multi select dropdown filter in Laravel 10 application. Here, the user can select multiple categories to filter products using the select option dropdown.

This filter is almost like a single select option filter. Just we will use the whereIn() method to accept multiple category IDs to filter the product. So let's see the example demo tutorial of dynamic multi-select dropdown and search Laravel.

laravel-10-multi-select-dropdown-filter

Step 1: Download Fresh Laravel 10

In the first step of the multiple dropdown filters in Laravel, download a fresh Laravel application by the following command:

composer create-project laravel/laravel example-app

 

Step 2: Create Migration

In this step, we need to create a migration and model for generating a products and categories table. So run the below command:

php artisan make:model Product -m
php artisan make:model Category -m

 

Now update the migration like below:

database/migrations

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('categories');
    }
};

 

And migrations for products table:

<?php

use App\Models\Category;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->foreignIdFor(Category::class);
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('products');
    }
};

 

And now update the model like

app/Models/Product.php

<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;

    protected $guarded = [];

    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}

 

Now update the category model like:

app/Models/Category.php

<?php

namespace App\Models;

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

class Category extends Model
{
    use HasFactory;

    protected $guarded = [];
}

 

Step 3: Connect database

In this step, we will connect the database, and I am going to use MySQL. So connect it like the below by updating the .env file:

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tutorial
DB_USERNAME=root
DB_PASSWORD=

 

Now run the migration command:

php artisan migrate

 

Read also: Laravel 10 Algolia Full Text Search Tutorial

 

Step 4:  Create Route

Now in this, I will use one route for how to filter data in multi select dropdown in Laravel.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\SearchController;

Route::get('product', [SearchController::class, 'index'])
    ->name('product.search');

 

Step 5: Create Controller

Now in this step, we have to create a SearchController to define this index method for how to apply multiple filter in laravel?

php artisan make:controller SearchController

 

Now update the controller like this:

app/Http/Controllers/SearchCountroller.php

<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;

class SearchController extends Controller
{
    public function index(Request $request)
    {
        $products = Product::orderBy('id', 'desc')
            ->with('category')
            ->when($request->category_id, function ($query) use ($request) {
                $query->whereIn('category_id', $request->category_id);
            })
            ->paginate(5);

        return view('product.index', compact('products','request'));
    }
}

 

Step 6: Create Views

We are almost there. Just we have to create our list file with all the product lists with the multi select filter form.

  • index.balde.php
  • app.blade.php

So create these files inside the following path and update them like below:

resources/views/layouts/app.blade.php

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>{{ config('app.name', 'Laravel') }}</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body style="background: #ddd;">
    <div id="app">
        <nav class="navbar navbar-default navbar-static-top">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse" aria-expanded="false">
                        <span class="sr-only">Toggle Navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="{{ url('/employee') }}" style="margin-left:190px;">Laravelia</a>
                </div>
                <div class="collapse navbar-collapse" id="app-navbar-collapse">
                    <ul class="nav navbar-nav">
                        &nbsp;
                    </ul>
                        <ul class="nav navbar-nav navbar-right" style="margin-right:190px;">
                        @guest
                            <li><a href="{{ route('login') }}">Login</a></li>
                            <li><a href="{{ route('register') }}">Register</a></li>
                        @else
                            <li class="dropdown">
                                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false" aria-haspopup="true">
                                    {{ Auth::user()->name }} <span class="caret"></span>
                                </a>
        
                                <ul class="dropdown-menu">
                                    <li>
                                        <a href="{{ route('account.index') }}">Account</a>
                                    </li>
                                    <li>
                                        <a href="{{ route('logout') }}"
                                            onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                            Logout
                                        </a>
        
                                        <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                                            {{ csrf_field() }}
                                        </form>
                                    </li>
                                </ul>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>        
        <div class="container">
            <div class="col-md-2"></div>
            <div class="col-md-8">
                @yield('content')
            </div>
            <div class="col-md-2"></div>
        </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</body>
</html>

 

This page for showing all the product lists.

resources/views/product/index.blade.php

@extends('layouts.app')

@section('content')
    <div class="panel panel-default">
        <div class="panel-body">
            <form action="{{ route('product.search') }}" method="get">
                 <div class="row">
                    <div class="col-md-10 form-group">
                        <label for="">Category</label>
                        <select name="category_id[]" class="form-control" multiple>
                            @foreach (\App\Models\Category::all() as $item)
                            <option value="{{ $item->id }}" {{ !is_null($request->category_id) ? in_array($item->id,$request->category_id) ? 'selected' : '' : '' }}>{{ $item->name }}</option>
                            @endforeach
                        </select>
                     </div>
                     <div class="col-md-2 form-group" style="margin-top:25px;">
                        <input type="submit" class="btn btn-primary" value="Filter">
                     </div>
                 </div>
            </form>
            <strong>Product List</strong>
            <table class="table table-responsive table-bordered table-stripped" style="margin-top:10px;">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Name</th>
                        <th>Category</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach ($products as $product)
                    <tr>
                        <td>{{ $product->id }}</td>
                        <td>{{ $product->name }}</td>
                        <td>{{ $product->category->name }}</td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
            {{ $products->links() }}
        </div>
    </div>
@endsection

 

Read also: Dropdown Search Filter In Laravel 10 Tutorial

 

Now all are set to go. Now run php artisan serve command to start the development server and visit the following URL to check multiple search filter in laravel.

URL
http://localhost:8000/product

 

Conclusion

Now we know multi select dropdown filter in laravel and How to apply multiple filter in laravel?. Hope this dynamic multi-select dropdown and search laravel tutorial will help you.

Category : #laravel

Tags : #laravel , #laravel search