Showing posts with label laravel dynamic dependant select box using livewire. Show all posts
Showing posts with label laravel dynamic dependant select box using livewire. Show all posts

Laravel Livewire Dependant Dropdown Tutorial

Laravel Livewire Dependant Dropdown Tutorial

Hii Guys,

Today,I learn you how to create on dependant dropdown with livewire in laravel application. I am going to do a simple laravel dependent dropdown using livewire. In this simple example through we understand how to work dependent dropdown in laravel livewire even if you beginner. you will able to create dynamic dependent dropdown in laravel livewire.

I sometimes require to make dependent dropdown like when state select at that time bellow city drop down list should change, i mean related to selected state. In this example i have two tables and there are listed bellow:

1. state 2. cities

So, when user will change state at that time, dynamically change city drop down box from database using laravel livewire. you can implement this example in your application by follow bellow few step.

Step 1 : Install Laravel App

In First step, We need to get fresh laravel version application using bellow command. So Let's open terminal and run bellow command.

composer create-project --prefer-dist laravel/laravel blog
Step 2 : Setup Database Configuration

After successfully install laravel app thenafter configure databse setup. We will open ".env" file and change the database name, username and password in the env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password
Step 3 : Create Migration and Model

In first step we have to create migration for state and cities tables using Laravel php artisan command, so first fire bellow command:

php artisan make:migration create_state_city_tables

After this command you will find one file in following path database/migrations and you have to put bellow code in your migration file for create tables.

database/migrations/2021_01_01_073031_create_state_city_tables.php
<?php

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

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


        Schema::create('cities', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('state_id');
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('cities');
        Schema::drop('state');
    }
}

Now you can create State and City model for using laravel php artisan command So let's run bellow command one by one:

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

Now open model file and put the bellow code:

app/Models/State.php
<?php

namespace App\Models;

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

class State extends Model
{
    use HasFactory;
    protected $table = 'state';
    protected $fillable = ['name'];
}
app/Models/City.php
<?php

namespace App\Models;

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

class City extends Model
{
    use HasFactory;
    protected $table = 'cities';
    protected $fillable = ['state_id', 'name'];
}
Step 4 : Install Livewire

In this step, You will simply install livewire to our laravel application using bellow command:

composer require livewire/livewire
Step 5 : Create Component

Now, You can create livewire component using bellow command, So Let's run bellow command to create statecity dropdown component:

php artisan make:livewire statecity 

Now they created fies on both path:

app/Http/Livewire/Statecity.php
resources/views/livewire/statecity.blade.php

Now first file we will update as bellow for Users.php file.

app/Http/Livewire/Users.php
<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\City;
use App\Models\State;

class Statecity extends Component
{
    public $states;
    public $cities;

    public $selectedState = NULL;

    public function mount()
    {
        $this->states = State::all();
        $this->cities = collect();
    }

    public function render()
    {
        return view('livewire.statecity');
    }

    public function updatedSelectedState($state)
    {
        if (!is_null($state)) {
            $this->cities = City::where('state_id', $state)->get();
        }
    }
}
Step 6 : Add Route

now, we need to add route for dynamic dependant dropdown with livewire in laravel application. so open your "routes/web.php" file and add following route.

routes/web.php
Route::view('states-city','livewire.home');
Step 7 : Create View

Here, we will create blade file for call state and city dependant dropdown route. in this file we will use @livewireStyles, @livewireScripts and @livewire('statecity'). so let's add it.

resources/views/livewire/home.blade.php

<html>
<head>
    <title>Laravel Livewire Dependant Dropdown</title>
    <script src="{{ asset('js/app.js') }}" defer></script>
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    @livewireStyles
</head>
<body>
    <div class="container">
        <div class="row justify-content-center mt-5">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header bg-dark text-white">
                        <h3>Laravel Livewire Dependant Dropdown</h3>
                    </div>
                    <div class="card-body">
                        @livewire('statecity')
                    </div>
                </div>
            </div>
        </div>
    </div>
    @livewireScripts
</body>
</html>
resources/views/livewire/statecity.blade.php
<div>
    <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>

Now we are ready to run our example so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/states-city

It will help you..