Laravel Vuejs Dependent Dropdown Example Tutorial

Throughout, Laravel 9 Vue.js dependent dropdown example tutorial, you will learn how to implement dependent dropdown with Vue js components in laravel. You can imlement this example in your laravel 5, laravel 6, laravel 7, laravel 8 or laravel 9 application as well.

Many times we need to retrieve data according to selected dropdown and display data on Vue components. So this tutorial will guide you step by step to build a dependent dropdown app with Vue js in laravel. as well as how to retrieve and render data on view components.

How to make dependent dropdown with Laravel & Vue.js

Follow the following stes to make dependent dropdown with Vue.js and Laravel 9 application:

  • Step 1: Install Laravel App
  • Step 2: Setup Database Configuration
  • Step 3: Create Model and Migrations
  • Step 4: Define Routes
  • Step 5: Create Controller
  • Step 6: NPM Configuration
  • Step 7: Create Vue Component
  • Step 8: Initialize Vue Components with Laravel
  • Step 9: Run Laravel Application

Install Laravel App

First you need to install a new laravel app using the following command:

composer create-project --prefer-dist laravel/laravel dropdown-dependend

Go inside the app

cd dropdown-dependend

Setup Database Configuration

Update your database credentials in your .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

Create Model & Run Migration

Now we need to create model and migration files. First we will create country model and migration using the below command.

Country Country Model & Migration:

php artisan make:model Country -m

Update fillable property in your country model just like below.

app/Models/Country.php

<?php

namespace App\Models;

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

class Country extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'code'
    ];
}

database\migrations\2022_02_06_062818_create_countries_table.php

<?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->string('code');
            $table->timestamps();
        });
    }

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

Now we will generate state model and migration file using the following command:

State Model & Migration:

php artisan make:model State -m 

Update the fillable property in State model.

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 $fillable = [
        'name', 'country_id'
    ];
}

database\migrations\2022_02_06_062818_create_states_table.php

<?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->string('name');
            $table->integer('country_id');
            $table->timestamps();
        });
    }

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

After all database related works we will run the migrate command and generate database tables:

php artisan migrate

Add Routes

Update your routes in your api.php file.

routes/api.php

use App\Http\Controllers\CountryStateController;
 
Route::get('get-countries', [CountryStateController::class, 'getCountries']);
Route::post('get-states', [CountryStateController::class, 'getStates']);

Update your routes web.php for api related works.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

Route::get('{any}', function () {
    return view('layouts.app');
})->where('any', '.*');

Create Controller

Next step, open command prompt and run the following command to create a controller by an artisan:

php artisan make:controller CountryStateController

After that, go to app\Http\Controllers and open CountryStateController.php file. Then update the following code into CountryStateController.php file:

app\Http\Controllers\CountryStateController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Country;
use App\Models\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);
    }
}

NPM Configuration in Laravel

Install all Vue dependencies:

npm install

To calling Laravel API routes. we need to install vue-axios. So use run the following command on command prompt:

npm install vue-axios --save

After installing all dependencies run this command:

npm run watch

Create Vue Component

Next step, go to resources/assets/js/components folder and create a filed called DropdownComponent.vue.

resources\js\components\DropdownComponent.vue

<template>
    <div class="container">
        <div class="text-center" style="margin: 20px 0px 20px 0px;">
            <span class="text-secondary">Laravel 9 vue.js Dependent Dropdown Example</span>
        </div>
        <div class="row justify-content-center" style="margin: 20px 0px 20px 0px;">
            <div class="col-md-8">
                <div class="card">
                    <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 {
        data(){
            return {
                country: 0,
                countries: [],
                state: 0,
                states: []
            }
        },
        created () {
            this.getCountries()
        },
        methods:{
            getCountries () {
                axios.get('http://127.0.0.1:8000/get-countries')
                    .then(function (response) {
                        this.countries = response.data;
                    }.bind(this));
            },
            getStates () {
                axios.get('http://127.0.0.1:8000/get_states', {
                    params: {
                        country_id: this.country
                    }
                }).then(function(response){
                    this.states = response.data;
                }.bind(this));
            }
        }
    }
</script>

Now open resources/assets/js/app.js and include the DropdownComponent.vue component like this:app.js

resources\js\app.js

 require('./bootstrap');
 import Vue from 'vue'; // if this is not work add this =>  window.Vue = require('vue');

 import axios from 'axios';
 import VueAxios from 'vue-axios';

 Vue.use(VueRouter);
 Vue.use(VueAxios, axios);
 Vue.component('dropdown-component', require('./components/DropdownComponent.vue').default);

 const app = new Vue({
     el: '#app',
     render: h => h(App),
 });

Initialize Vue Components with Laravel

Next, Navigate to resources/views/layouts and open app.blade.php file. Then update the following code into app.blade.php file as follow:

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" value="{{ csrf_token() }}"/>
    <title>How to make dependent dropdown with Vue. js and Laravel</title>
    <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet" type="text/css">
    <link href="{{ mix('css/app.css') }}" type="text/css" rel="stylesheet"/>
</head>
<body>
<div id="app">
    <dropdown-component></dropdown-component>
</div>
<script src="{{ mix('js/app.js') }}" type="text/javascript"></script>
</body>
</html>

Run Laravel Application

Run the following command to start development server:

php artisan serve

and run npm

npm run watch

Hope you enjoye laravel vue dependent dropdown example tutorial.

Leave a Comment