Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

How to change city dropdown changes automatically after selecting state dropdown changes

To dynamically change the state dropdown based on the selected country in Laravel, you can use JavaScript/jQuery to handle the change event of the country dropdown and make an AJAX request to fetch the corresponding states for the selected country. Here's an example of how you can achieve this:

Set up the route in your web.php file to handle the AJAX request:

// routes/web.php

use App\Http\Controllers\CountryController;

Route::get('/get-states/{countryId}', [CountryController::class, 'getStates']);
Enter fullscreen mode Exit fullscreen mode

Create a controller named CountryController and define a method to fetch the states for the selected country:

// app/Http/Controllers/CountryController.php

namespace App\Http\Controllers;

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

class CountryController extends Controller
{
    public function getStates($countryId)
    {
        $states = State::where('country_id', $countryId)->get(); // Retrieve states based on the selected country

        return response()->json($states);
    }
}
Enter fullscreen mode Exit fullscreen mode

Update your view file with the country and state dropdowns:

<html>
<head>
    <title>Country and State Dropdown</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#country').change(function() {
                var countryId = $(this).val();
                if (countryId) {
                    $.ajax({
                        url: '/get-states/' + countryId,
                        type: 'GET',
                        success: function(data) {
                            $('#state').empty();
                            $.each(data, function(key, value) {
                                $('#state').append('<option value="' + value.id + '">' + value.name + '</option>');
                            });
                        }
                    });
                } else {
                    $('#state').empty();
                }
            });
        });
    </script>
</head>
<body>
    <h2>Select Country and State</h2>

    <div class="form-group">
        <label for="country">Country:</label>
        <select id="country" class="form-control">
            <option value="">Select Country</option>
            @foreach ($countries as $country)
                <option value="{{ $country->id }}">{{ $country->name }}</option>
            @endforeach
        </select>
    </div>

    <div class="form-group">
        <label for="state">State:</label>
        <select id="state" class="form-control">
            <option value="">Select State</option>
        </select>
    </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In the above example, the JavaScript/jQuery code listens for the change event of the country dropdown (#country). When the country is selected, an AJAX request is made to the /get-states/{countryId} route, where {countryId} is the selected country's ID.

The getStates() method in the CountryController fetches the states based on the selected country's ID and returns them as a JSON response.

The returned states are then dynamically added to the state dropdown (#state) using the .append() method.

Make sure to adjust the model names, table names, and column names according to your application's database schema.

===============================================

blade file

<div class="col-md-3">  
                            <select id="select_state_id" class="selectpicker form-control @error('state_id') is-invalid @enderror" name="state_id" data-live-search="true">
                            <option value="">Select a state</option>
                            @foreach ($state as $id => $state_name)
                                    <option value="{{ $id }}">{{ $state_name }}</option>
                                @endforeach
                            </select>    
                            @error('state_id')
                            <span class="invalid-tooltip">
                                <strong>{{ $message }}</strong>
                            </span>
                            @enderror
                        </div>
Enter fullscreen mode Exit fullscreen mode

In jquey and ajax

    $('#select_state_id').change(function() {
                console.log('inside select sate');
                var stateId = $(this).val();
                if (stateId) {
                    $.ajax({
                        url: '/get-cities/' + stateId,
                        type: 'GET',
                        success: function(data) {
                            $('#select_city_id').empty();
                            $.each(data, function(key, value) {
                                $('#select_city_id').append('<option value="' + value.id + '">' + value.city_name + '</option>');
                            });
                        }
                    });
                } else {
                    $('#state').empty();
                }
            });
Enter fullscreen mode Exit fullscreen mode

In Route

   Route::get('/get-cities/{stateId}', 'PagesController@getcities')->name('page.getcities');
Enter fullscreen mode Exit fullscreen mode

In Controller

    public function getcities($stateId)
    {
        $cities =DB::table('broker')->leftJoin('cities', 'broker.city_id', '=', 'cities.id')->where('broker.state_id', $stateId)->groupby('broker.city_id')->get(); // Retrieve states based on the selected country

        return response()->json($cities);
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)