How to Build Dependent Dropdown with Laravel 10 Livewire

Last Updated on by in Laravel

In this comprehensive tutorial, you will learn how to create a dependent dropdown feature using the powerful Laravel Livewire framework. This tutorial is designed to guide you through each step of the process, enabling you to integrate dynamic dropdowns that change based on user selections.

What is a Dependent Dropdown?

A dependent dropdown is a user interface element that shows different options based on the selection in another dropdown. This feature is useful for providing a smooth, dynamic user experience in forms, filtering options, or any scenario where the choices in one dropdown depend on another.

Why Laravel Livewire?

Laravel Livewire is a modern framework that streamlines the development of interactive components in Laravel. It seamlessly integrates the simplicity of traditional server-side rendering with the reactivity of front-end frameworks, providing a fluid development experience.

Tutorial Objective:

  • To teach you how to create a dependent dropdown using Laravel Livewire.
  • To show you how to dynamically update dropdown options based on user input.

What We’ll Cover:

  • Setting Up Livewire: Installing and configuring Livewire in a Laravel project.
  • Creating the Component: Building a Livewire component to manage the dependent dropdown functionality.
  • Data Binding and Events: Learning how to bind data and use Livewire events for dynamic updates.
  • Creating Dependent Dropdowns: Implementing the logic to change dropdown options based on the selection in another dropdown.
  • Testing and Debugging: Ensuring the dropdowns work as expected and troubleshooting any issues.

By the end of this tutorial, you’ll be equipped with the knowledge to implement dependent dropdowns in your Laravel projects using the simplicity and power of Livewire. Let’s get started!

Step-by-Step Guide to Building a Laravel Livewire Dependent Dropdown

  • Create Laravel App
  • Include Database Details
  • Create Model and Migration
  • Add Livewire Library
  • Build Livewire Dependent Controller
  • Set Up View File
  • Create New Routes
  • Run Development Server

Create Laravel App

The first requires a code editor and a composer tool installed on your system. On the console, add the given command and then hit enter.

composer create-project laravel/laravel --prefer-dist laravel-demo
cd laravel-demo

Include Database Details

Open the .env file, here in this file you have to add the database credentials.

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=

For macOS MAMP PHP server; make sure to additionally include UNIX_SOCKET and DB_SOCKET right below the database details in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Create Model and Migration

We have to generate a new migration table to add a new property in the table.

php artisan make:migration create_category_products_tables

You have to look for the create_category_products_tables.php file; you can find this file in the database/migrations directory.

<?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::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->integer('product_id');
            $table->string('name');
            $table->timestamps();
        });        
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categories');
        Schema::dropIfExists('products');
    }
};

We created the migration file, and now you need to generate the models; make sure to invoke the given command.

php artisan make:model Category
php artisan make:model Product

After running the above command, you have to go directly to the app/Models/ folder, open the Category.php file, and insert the given code.

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
    
    use HasFactory;
    protected $fillable = ['name'];
}

There you must be seeing the app/Models/Product.php file make sure to put the given code into the file.

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
    use HasFactory;
    protected $fillable = ['product_id', 'name'];
}

Now the model and migration files are ready, and we can use the artisan command to add them to the database.

php artisan migrate

Add Livewire Library

The next task is to install the Livewire package in the laravel; you need to type the command on the console then hit enter.

composer require livewire/livewire

Build Livewire Dependent Controller

You can quickly generate the controller using the composer command.

php artisan make:livewire categoryproductdropdown

The livewire composer command generates the following files:

Then, you must head over to the app/Http/Livewire/ directory and look for the Categoryproductdropdown.php file and add the code into the file.

<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Category;
use App\Models\Product;
class Categoryproductdropdown extends Component
{
    public $categories;
    public $products;
   
    public $selectedCategory = NULL;
   
    public function mount()
    {
        $this->categories = Category::all();
        $this->products = collect();
    }
   
    public function render()
    {
        return view('livewire.categoryproductdropdown')->extends('layouts.app');
    }
   
    public function newSelectedCategory($category)
    {
        if (!is_null($category)) {
            $this->products = Product::where('product_id', $category)->get();
        }
    }    
}

In this step, you require to move into the resources/views/livewire directory here, you have to add the suggested code to the categoryproductdropdown.blade.php file.

<div>
    <h2 class="mb-4">Laravel Dynamic Livewire Dependant Dropdown Example</h2>
    <div class="form-group row">
        <label for="category" class="col-md-4 text-md-right"><strong>Category</strong></label>
        <div class="col-md-6">
            <select wire:model="selectedCategory" class="form-control">
                <option value="" selected>Select category</option>
                @foreach($categories as $category)
                    <option value="{{ $category->id }}">{{ $category->name }}</option>
                @endforeach
            </select>
        </div>
    </div>
   
    @if (!is_null($selectedCategory))
        <div class="form-group row">
            <label for="product" class="col-md-4 text-md-right">Product</label>
   
            <div class="col-md-6">
                <select class="form-control" name="city_id">
                    <option value="" selected>Choose product</option>
                    @foreach($products as $product)
                        <option value="{{ $product->id }}">{{ $product->name }}</option>
                    @endforeach
                </select>
            </div>
        </div>
    @endif
</div>

Set Up View File

In this step, we will set up the livewire view template; for that you need to create the layouts/ folder in resources/views/ directory then you have to create the app.blade.php file and add the given code into the file.

Full path: resources/views/layouts/app.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Livewire Dropdown Tutorial</title>
    @livewireStyles
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
     
<div class="container mt-5">
    @yield('content')
</div>
     
</body>
   
@livewireScripts
   
</html>

Create New Routes

Next, you have to open the routes/web.php file; here you have to define the route.

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Livewire\Categoryproductdropdown;
/*
|--------------------------------------------------------------------------
| 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('/dependent-dropdown', Categoryproductdropdown::class);

Run Development Server

Type the given command on the console and press enter to start the application server.

php artisan serve

Here is the url that you can use to view the app.

http://127.0.0.1:8000/dependent-dropdown

How to Build Dependent Dropdown with Laravel Livewire

Conclusion

By the end of this tutorial, you will have learned how to build dependent dropdowns using Laravel Livewire. This feature will enhance your web applications by providing a more dynamic and interactive user experience.

With Livewire, you can easily manage data binding and update dropdown options as needed. We hope this tutorial helps you create more user-friendly and efficient interfaces in your Laravel projects.

Happy coding!

Age calculator tool

🎂✨ Discover your age in detail and with countdown to your next birthday with fun facts! 🎈🎉

Calculate your age now!
Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.