Laravel 8 and Vue.js Country state dependant dropdown

By | May 11, 2021

Hello Coders!!
This article is about the Laravel 8 and Vue.js Country state dependant dropdown.

In this article, we are installing Laravel 8 along with vue js and then we will make a feature of country state dependency dropdown.

Steps: Five easy steps for setup

  1. Install Laravel 8
  2. Install Vue js
  3. Create Migration files
  4. Create Model, controller files, and Routes
  5. Write Vue code

Step 1: Install Laravel 8


The first and foremost step is to install the latest laravel in your system so for that you need to run the below command in your working directory.

composer create-project --prefer-dist laravel/laravel cs-laravelvue

This command will install the latest laravel 8 in your system. Now you need to set up the database credentials to complete the installation.

In case you need to check the laravel installation article then you check here Laravel Installation.

Step 2: Install Vue js


To install vue js in your freshly installed laravel you need to go inside to just created the project and run the below commands.

composer require laravel/ui
installation of laravel ui
installation of laravel/ui
php artisan ui vue
npm install && npm run dev

After running the above command run the below commands again.

npm install
npm run dev
Build successful
Build successful

Step 3: Create Migration files


Now we are going to create the migration files for the country and state tables. So for that run, the below commands in your terminal.

php artisan make:migration create_countries_table
php artisan make:migration create_states_table

This will create two migration files in your migrations folder. Open that files and add the below codes to them.

Country Migration file

<?php

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

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

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

State Migration file

<?php

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

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

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

Now migrate these tables into the database by running the below command.

php artisan migrate

This command will be migrating all the tables in the database. And in the database, you will see the tables along with countries and states. Just add some dummy data in countries and state tables like this.

Country
Country
States
States

Step 4: Create Model, controller files and Routes


To create the model and controller file run the below command in your terminal.

php artisan make:model Country
php artisan make:model States
php artisan make:controller APIController

These three commands will create the models and controller file. Add the below code in the controller file.

APIController.php file

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Country;
use App\Models\States;

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 = States::where('country_id', $request->country_id)->get();

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

Add Routes in routes/api.php file

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\APIController;


Route::get('/getCountries', [APIController::class, 'getCountries']);
Route::get('/getStates', [APIController::class, 'getStates']);

Step 5: Write Vue code


Open “resources/js/components/ExampleComponent.vue” and write this code in it.

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Laravel 8 and Vue Dependent Dropdown Example - codescompanion.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>

Update 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 8 and Vue Dependent Dropdown Example - codescompanion.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 run the below command to update the app.js file.

npm run dev
Laravel 8 and Vue Dependent Dropdown Example
Laravel 8 and Vue Dependent Dropdown Example

We are done here and you can use this snippet anywhere you want. So this is the article about the Laravel 8 and Vue.js Country state dependant dropdown. Happy Coding !!

Here is the Github link for this demo.

Leave a Reply

Your email address will not be published. Required fields are marked *