Saturday, November 16, 2024
Google search engine
HomeLanguagesLaravel 9 Livewire Dependent Dropdown Example

Laravel 9 Livewire Dependent Dropdown Example

Laravel 9 livewire dependant dropdown example; In this tutorial, we will learn how to make dependent dropdown using livewire in laravel 9 app.

Laravel 9 Dynamic Dependent Dropdown with Livewire

Follow the following steps to make dependent dropdown with livewire in laravel 9 apps:

  • Step 1: Install Laravel 9 App
  • Step 2: Add Database Detail
  • Step 3: Create Migration For File using Artisan
  • Step 4: Create Model File
  • Step 5: Install Livewire Package
  • Step 6: Create Dependent Dropdown Component using Artisan
  • Step 7: Add Route For Livewire Dependent Dropdown
  • Step 8: Create View File
  • Step 9: Run Development Server

Step 1: Install Laravel 9 App

First of all, Open terminal OR command prompt and run the following command to install laravel fresh app for laravel livewire dependent dropdown app:

 composer create-project --prefer-dist laravel/laravel blog 

Step 2: Add Database Detail

In this step, Add database credentials in the .env file. So open project root directory and find .env file. Then add database detail in .env file:

DB_CONNECTION=mysql  
DB_HOST=127.0.0.1  
DB_PORT=3306  
DB_DATABASE=here database name here 
DB_USERNAME=here database username here 
DB_PASSWORD=here database password here

Step 3: Create Migration For File using Artisan

In this step, generate model and migration file using the following command:

php artisan make:migration create_states_cities_tables

So, Navigate to database/migrations folder and open create_states_cities_tables.php file. Then update the following code into create_states_cities_tables.php file:

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
class CreateStatesCitiesTables extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('states', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
  
        Schema::create('cities', function (Blueprint $table) {
            $table->id();
            $table->integer('state_id');
            $table->string('name');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('states');
        Schema::dropIfExists('cities');
    }
}

Step 4: Create Model File

In this step, open terminal and execute the following commands to create model files:

php artisan make:model State
php artisan make:model City

Then visit app/Models/ directory and open state.php file and add the following code into it:

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

Then visit app/Models/ directory and open city.php file and add the following code into it:

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

Now, open command prompt and run the following command to create the table into database:

php artisan migrate

Step 5: Install Livewire Package

In this step, we need to install livewire package to laravel project using the following command:

composer require livewire/livewire

Step 6: Create Dependent Dropdown Component using Artisan

In this step, create the livewire components for creating a livewire dependent dropdown component using the following command. So Open cmd and run the following command:

php artisan make:livewire statecitydropdown

This command will create the following components on the following path:

app/Http/Livewire/Statecitydropdown.php

resources/views/livewire/statecitydropdown.blade.php

Now, Navigate to app/Http/Livewire folder and open Statecitydropdown.php file. Then add the following code into Statecitydropdown.php file:

<?php
  
namespace App\Http\Livewire;
  
use Livewire\Component;
use App\Models\City;
use App\Models\State;
  
class Statecitydropdown extends Component
{
    public $states;
    public $cities;
  
    public $selectedState = NULL;
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function mount()
    {
        $this->states = State::all();
        $this->cities = collect();
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function render()
    {
        return view('livewire.statecitydropdown')->extends('layouts.app');
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function updatedSelectedState($state)
    {
        if (!is_null($state)) {
            $this->cities = City::where('state_id', $state)->get();
        }
    }
    
}

After that, Navigate to resources/views/livewire folder and open statecitydropdown.blade.php file. Then add the following code into statecitydropdown.blade.php file:

<div>
    <h1>Laravel 9 Livewire Dependant Dropdown - Tutsmake.com</h1>
    <div class="form-group row">
        <label for="state" class="col-md-4 col-form-label text-md-right">State</label>
        <div class="col-md-6">
            <select wire:model="selectedState" class="form-control">
                <option value="" selected>Choose state</option>
                @foreach($states as $state)
                    <option value="{{ $state->id }}">{{ $state->name }}</option>
                @endforeach
            </select>
        </div>
    </div>
  
    @if (!is_null($selectedState))
        <div class="form-group row">
            <label for="city" class="col-md-4 col-form-label text-md-right">City</label>
  
            <div class="col-md-6">
                <select class="form-control" name="city_id">
                    <option value="" selected>Choose city</option>
                    @foreach($cities as $city)
                        <option value="{{ $city->id }}">{{ $city->name }}</option>
                    @endforeach
                </select>
            </div>
        </div>
    @endif
</div>

Step 7: Add Route For Livewire Depedent Dropdown

In this step, Navigate to routes folder and open web.php. Then add the following routes into web.php file:

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

Step 8: Create View File

In this step, navigate to resources/views/livewire folder and create one blade view files that name app.blade.php file. Then add the following code into app.blade.php file:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 Livewire Dependent Dropdown Example - Tutsmake.com</title>
    @livewireStyles
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
</head>
<body>
    
<div class="container">
    @yield('content')
</div>
    
</body>
  
@livewireScripts
  
</html>
Note that, if you want to add HTML(blade views), CSS, and script code into your livewire files. So, you can use @livewireStyles, @livewireScripts, and @livewire(‘ blade views’).

Step 9: Run Development Server

Finally, we need to run the PHP artisan serve command to start laravel livewire dependent dropdown app:

php artisan serve

If we want to run the project diffrent port so use this below command 

php artisan serve --port=8080  

Now, we are ready to run laravel 9 livewire dependent dropdown app. So open browser and hit the following URL into browser:

localhost:8000/statecitydropdown

Recommended Laravel Tutorials

RELATED ARTICLES

Most Popular

Recent Comments