How to make dependent dropdown with Vue.js and Laravel

How to make dependent dropdown with Vue.js and Laravel

In this tutorial, I would like to share with you to create dependent dropdown with Vue.js and Laravel 5.8

I will create simple example of Laravel Vue dependent dropdown example. We will create country state city dependent dropdown using Laravel 5.8 and Vue js.

Now days, all are using Vue js with Laravel, so might be sometime we need to create function like dependent dropdown with country state city dropdown. So i will help you to create dependent dropdown using Vue.js, Axios, API and Laravel 5.8.

In this example, I created two tables "countries" and "states". Then I created two get API that will return data. Then we will write code for Vue.js and component, we will create two dropdown with Ajax code using Axios. You can see bellow preview and download source code.

Step 1 : Install Laravel 5.8 App

In the first step, we require to get fresh Laravel 5.8 application using bellow command, So open your terminal OR command prompt and run bellow command:

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

Step 2: Create Country and State Table

in second step, we have to create migration for "countries" and "states" table using Laravel 5.8 **[PHP](https://morioh.com/topic/php "PHP**") artisan command, so first fire bellow command:

php artisan make:migration create_countries_table

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 posts table.

<?php

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

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

        Schema::create('states', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('country_id');
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('countries');
        Schema::dropIfExists('states');
    }
}

After create migration we need to run above migration by following command:

php artisan migrate

Step 3: Create Country and State Model

In this step, we need to create two model for country and state. So let's run bellow command and create model.

php artisan make:model Country

app/Country.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Country extends Model
{

}
php artisan make:model State

app/State.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class State extends Model
{

}

After create migration and model, Make sure you have to add some dummy records in your "countries" and "states" table.

Step 4: Create API

In this step, we will create two api route for getting data. So, let's add new route on that file.

routes/api.php

Route::get('getCountries', '[email protected]');
Route::get('getStates', '[email protected]');

Step 5: Create APIController

in this step, now we have create APIController with two methods, in this method we will return data. So let's create controller:

app/Http/Controllers/APIController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Country;
use App\State;

class APIController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function getCountries()
    {
        $data = Country::get();

        return response()->json($data);
    }

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function getStates(Request $request)
    {
        $data = State::where('country_id', $request->country_id)->get();

        return response()->json($data);
    }
}

Step 6: NPM Configuration

In this step, we have to first add setup of Vue.js and then install npm, so let's run bellow command in your project.

Install vue:

php artisan preset vue

Install npm:

npm install

Step 7: Update Components

Here, we will write code on components, So let's update file and put bellow code:

resources/assets/js/components/ExampleComponent.vue

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Laravel Vue Dependent Dropdown Example - ItSolutionStuff.com</div>

                    <div class="card-body">
                        <div class="form-group">
                            <label>Select Country:</label>
                            <select class='form-control' v-model='country' @change='getStates()'>
                              <option value='0' >Select Country</option>
                              <option v-for='data in countries' :value='data.id'>{{ data.name }}</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Select State:</label>
                            <select class='form-control' v-model='state'>
                              <option value='0' >Select State</option>
                              <option v-for='data in states' :value='data.id'>{{ data.name }}</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>  
    export default {
        mounted() {
            console.log('Component mounted.')
        },
        data(){
            return {
                country: 0,
                countries: [],
                state: 0,
                states: []
            }
        },
        methods:{
            getCountries: function(){
              axios.get('/api/getCountries')
              .then(function (response) {
                 this.countries = response.data;
              }.bind(this));

            },
            getStates: function() {
                axios.get('/api/getStates',{
                 params: {
                   country_id: this.country
                 }
              }).then(function(response){
                    this.states = response.data;
                }.bind(this));
            }
        },
        created: function(){
            this.getCountries()
        }
    }
</script>

Step 8: Update welcome.blade.php

At last step, we will update our welcome.blade.php file. in this file we will use app.js file and use it, so let's update.

resources/views/welcome.blade.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel Vue Dependent Dropdown Example - ItSolutionStuff.com</title>
        <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css">
    </head>
    <body>
        <div id="app">
            <example-component></example-component>
        </div>
        <script src="{{asset('js/app.js')}}" ></script>
    </body>
</html>

Now you have to run below command for update app.js file:

npm run dev

Now you can check our example and also check demo and download free code.

You can download code from GitHub

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

PHP Web Application Development Company

As a top **PHP Web Application Development Company in USA**[https://www.dataeximit.com/php-development-services/](https://www.dataeximit.com/php-development-services/ "https://www.dataeximit.com/php-development-services/"), we at Data EximIT have...

Top Vue.js Developers in USA

Vue.js is an extensively popular JavaScript framework with which you can create powerful as well as interactive interfaces. Vue.js is the best framework when it comes to building a single web and mobile apps.

Develop this one fundamental skill if you want to become a successful developer

Throughout my career, a multitude of people have asked me&nbsp;<em>what does it take to become a successful developer?</em>