How to Build Dependent Dropdown with Laravel 10 Livewire

Last Updated on by in Laravel

In this tutorial, we are learning how to build dynamic dependent dropdown in Laravel application using the laravel livewire package.

To implement dependent dropdown in laravel, we will need to create a basic laravel app, connect the app to the database, set up some migrations and models and create a livewire view and controller.

Laravel Livewire is a powerful library that helps you build modern, reactive, dynamic web applications using Laravel Blade.

The dependent dropdown allows you to filter the options in a given list relative to the option we picked. In this livewire-dependent dropdown example, you will have to follow all the mentioned below steps.

Laravel 10 Livewire Dynamic Dependent Dropdown Example

  • 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

In this tutorial, we have discovered how to create a dependent dropdown list in the Laravel application using the laravel livewire package.

We hope you have understood the entire process and can easily add a dynamic dependent dropdown in laravel.