Filtering data with a select option in Laravel is very easy. It is not difficult like the search model. In this example, I will show you how to filter data from the dropdown in Laravel 10 application.

To create this dropdown filter in Laravel 10, I will use a product and category table where a product belongs to a relationship with a category and a category has many relationships with a product. So this tutorial is going to be very helpful for those who are going to learn How to filter data in dropdown Laravel 10.

So we need a view for showing the product list with a select option filter and one route to show products and filter products in Laravel 10. Let's see the preview of this tutorial:

laravel-10-dropdown-filter

Step 1: Download Fresh Laravel 10

In the first step of the dropdown filter 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

//and

php artisan db:seed

 

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 dropdown 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 laravel advanced search filter.

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->where('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 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">
                            @foreach (\App\Models\Category::all() as $item)
                            <option value="{{ $item->id }}" {{ $request->id === $item->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: Laravel 10 Search Query With Relationship Data

 

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

URL
http://localhost:8000/product

 

Conclusion

Now we know how to filter data in dropdown laravel and how to use search filter in Laravel 10 without a package. Hope this dropdown search filter in laravel.

Category : #laravel

Tags : #laravel , #laravel search