How To Create Dependent Dropdown In Laravel

In this example we will see how to create dependent dropdown list in laravel using ajax or laravel dynamic dependent dropdown using ajax.

Many times we have requirments of get dynamic data or value on change of dependent dropdown in our websites or project, So, here I will show you how to get dynamic data or value using ajax in dropdown.

Here, we are using 2 tables state and city and when user will selected any state at that time in dependent dropdown automatically value has been change. So, follow below steps and get output of dependent dropdown in laravel.

 

Step 1 : Create Migration

For this example we need to create migration for state and city tables.

php artisan make:migration create_state_tables
php artisan make:migration create_city_tables

 After that you will find 2 migrations in database/migrations folders we have to add below code for create new tables in database.

1) Add below code in CreateStateTable

<?php

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

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

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

2) Add below code in CreateCityTable

<?php

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

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

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

After that we need to migrate these 2 tables in database So, Run following command in your terminal to migrate these tables.

php artisan migrate

 

Step 2 : Add Route

Now, We need to add route for layouts and ajax request, So create 2 routes as below and add code in your app/Http/routes.php

<?php

use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

Route::get('dropdown','UserController@state');
Route::get('city/{id}','UserController@city');

 

 

Step 3 : Create Controller

Now, create new UserController controller in this path app/Http/Controllers/UserController.php and add below code in your controller.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use DB;

class UserController extends Controller
{
    public function state()
    {
        $states = DB::table("state")->pluck('name','id');        
        return view('index',compact('states'));
    }

    public function city($id)
    {
        $cities = DB::table("city")
                    ->where("state_id",$id)
                    ->pluck('name','id');
        return json_encode($cities);
    }

}

 

Step 4 : Create Blade file

We need to create blade file for view output, So create new blade file in following path and put bellow code:

resources/view/index.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Dependent Dropdown Example - techsolutionstuff.com</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
<div class="container">
    <h3 class="text-center" style="margin-bottom: 20px;">Laravel Dependent Dropdown Example - techsolutionstuff.com</h3>
     <div class="col-md-8 col-md-offset-2">
    	<div class="panel panel-default">
	      	<div class="panel-heading">Select State and Get Related City</div>
	      	<div class="panel-body">
	            <div class="form-group">
	                <label for="title">Select State:</label>
	                <select name="state" class="form-control">
	                    <option value="">Select State</option>
	                    @foreach ($states as $key => $value)
	                        <option value="{{ $key }}">{{ $value }}</option>
	                    @endforeach
	                </select>
	            </div>
	            <div class="form-group">
	                <label for="title">Select City:</label>
	                <select name="city" class="form-control">
	                </select>
	            </div>
	      	</div>
      	</div>
    </div>
</div>
<script type="text/javascript">
    $(document).ready(function() {
        $('select[name="state"]').on('change', function() {
            var stateID = $(this).val();
            if(stateID) {
                $.ajax({
                    url: '/city/'+stateID,
                    type: "GET",
                    dataType: "json",
                    success:function(data) {                      
                        $('select[name="city"]').empty();
                        $.each(data, function(key, value) {
                        $('select[name="city"]').append('<option value="'+ key +'">'+ value +'</option>');
                        });
                    }
                });
            }else{
                $('select[name="city"]').empty();
            }
        });
    });
</script>
</body>
</html>

 

Finally, We will get output like below screenshot.

laravel dynamic dependent dropdown using ajax

 


You might also like :

 

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS