How To Create Dependent Dropdown In Laravel

    In this article, we will see how to create a dependent dropdown list in laravel using ajax. Many times we have requirements to get dynamic data or value on change of dependent dropdown in our websites or project. So, here we will see how to get dynamic data or value using ajax in the dropdown.

    So, let's see a dependent dropdown in laravel and a dynamic dropdown example in laravel.

    Here, we are using two tables state and city and when the user will select any state at that time in the dependent dropdown automatically value has changed. So, follow the below steps and get the output of this example.

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 the 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 the 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 the database. So, Run the following command in your terminal to migrate these tables.

php artisan migrate
Step 2: Add Route

    Now, We need to add routes for layouts and ajax requests. 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','[email protected]');
Route::get('city/{id}','[email protected]');
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 a Blade file

    We need to create a blade file for view output. So, create a new blade file in the following path and put the below code.

    resources/view/index.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Dependent Dropdown Example - websolutionstuff.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 - websolutionstuff.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 the below screen print.

    dependent_dropdown

    You might also like:

Bình luận
Vui lòng đăng nhập để bình luận
Một số bài viết liên quan