Laravel 7 Vue Dependent Dropdown Example

Laravel Vue js dependent dropdown example tutorial, you will learn how to implement dependent dropdown with Vue js components in laravel.

Sometimes, you work with any laravel vue js apps. And you want 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.

Laravel Vue JS Dependent Dropdown Example

Follow the below steps and build laravel vue js dynamic dependent dropdown apps:

  • Step 1: Download Laravel Fresh App
  • Step 2: Add Database Detail
  • Step 3: Create Migration Files
  • Step 4: Create Models
  • Step 5: NPM Configuration
  • Step 6: Add Routes
  • Step 7: Create Controller By Command
  • Step 8: Create Vue Component
  • Step 9: Initialize Vue Components
  • Step 10: Run Development Server

Step 1: Download Laravel Fresh App

In this step, you need to install laravel latest application setup, So open your terminal OR command prompt and run the following command:

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

Step 2: Add Database Details

After successfully install laravel Application, Go to your project .env file and set up database credential and move next step:

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

Step 3: Create Migration Files

Next step, you need to run the following command:

php artisan make:migration create_countries_states_table

Now open create_countries_states_table.php migration file from database>migrations and replace up() function with the following code:

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCountriesStatesTable 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');
    }
}

Next, migrate the table using the below command:

php artisan migrate

Step 4: Create Models

Use the following laravel artisan commands to build country and state model inside your laravel app:

php artisan make:model Country
php artisan make:model State

Step 5: NPM Configuration

You need to setup Vue and install Vue dependencies using NPM. So run the following command on command prompt:

Install all Vue dependencies:

npm install

To calling Laravel API routes. You 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

Step 6: Add Routes

Next step, go to routes folder and open web.php file and add the following routes into your file:

routes/web.php

Route::get('get_countries', 'CountryStateController@getCountries');
Route::get('get_states', 'CountryStateController@getStates');

Step 7: Create Controller By Command

Next step, open your 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 your CountryStateController.php file:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Country;
use App\State;
class CountryStateController extends Controller
{
    /**
     * Retrieve countries data
     *
     * @return void
     */
    public function getCountries()
    {
        $data = Country::get();
        return response()->json($data);
    }
    /**
     * Retrieve states data
     *
     */
    public function getStates(Request $request)
    {
        $data = State::where('country_id', $request->country_id)->get();
        return response()->json($data);
    }
}

Step 8: Create Vue Component

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

And update the following code into your DropdownComponent.vue. components file:

<template>
    <div class="container">
        <div class="text-center" style="margin: 20px 0px 20px 0px;">
            <span class="text-secondary">Dependent Dropdown with Laravel and VueJS</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: []
            }
        },
        methods:{
            getCountries: function(){
                axios.get('/get_countries')
                    .then(function (response) {
                        this.countries = response.data;
                    }.bind(this));
            },
            getStates: function() {
                axios.get('/get_states',{
                    params: {
                        country_id: this.country
                    }
                }).then(function(response){
                    this.states = response.data;
                }.bind(this));
            }
        },
        created: function(){
            this.getCountries()
        }
    }
</script>

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

require('./bootstrap');
window.Vue = require('vue');
Vue.component('dropdown-component', require('./components/DropdownComponent.vue').default);
const app = new Vue({
    el: '#app',
});

Step 9: Initialize Vue Components

In this step, navigate to resources/views and create one folder named layouts. Inside this folder create one blade view file named app.blade.php file.

Next, Navigate to resources/views/layouts and open app.blade.php file. Then update the following code into your 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>Dependent Dropdown with Laravel and VueJS - Tutsmake.com</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>

Step 10: Run Development Server

Run the following command to start development server:

npm run dev
or
npm run watch

Conclusion

In this tutorial, you have learned how to build dependent dropdown app with Vue js in laravel.

Recommended Laravel Vue js Posts

Preview of your laravel 7 vue js dependent dropdown app as follow:

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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