Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

php - Laravel dynamic dropdown country and state

I'm trying to make two dropdown menus. These are the countries and states selections from my database. My problem is don't know how to make conditions that states must be dependent on countries. When I select [countryname] it will give a different selection of states name in my dropdown. So far here what I have done so far.

AdminController.php

public function user_register()
    {
        $countryname = DB::table('countries')
            ->get();
        $statename = DB::table('states')
            ->get();

        $title = ucwords(Lang::get('constants.user') . ' ' . Lang::get('constants.register')); 
        return View::make('register.user_register')
            ->with('title', $title)
            ->with('page', 'user_register')
            ->with('countryname', $countryname)
            ->with('statename', $statename)
    }

user_register.blade.php

<select class="form-control" id="countries" name="countries">
    <option value="">Please select</option>
        <?php foreach ($countryname as $key=>$countryname): ?>
        <option value="<?php echo $countryname->sortname; ?>"<?php
         if (isset($countries) && Input::old('countries') == $countryname->sortname) 
         {
             echo 'selected="selected"';
         }
         ?>>
         <?php  echo $countryname->sortname ." - ". $countryname->name  ; ?>
    </option>
    <?php endforeach; ?>
</select>


<select class="form-control" id="states" name="states">
    <option value="">Please select</option>
        <?php foreach ($statename as $key=>$statename): ?>
        <option value="<?php echo $countryname->name; ?>" <?php
        if (isset($states) && Input::old('states') == $statename->name)
        {
            echo 'selected="selected"';
        }
        ?>>
        <?php  echo $statename->name; ?></option>
        <?php endforeach; ?>
</select>

In my database

Table: countries

+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| country_id| int(11)      | NO   | PRI | NULL    | auto_increment |
| sortname  | varchar(3)   | NO   |     | NULL    |                |
| name      | varchar(150) | NO   |     | NULL    |                |
| phonecode | int(11)      | NO   |     | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+

Table: states

+------------+------------------+------+-----+---------+----------------+
| Field      | Type             | Null | Key | Default | Extra          |
+------------+------------------+------+-----+---------+----------------+
| id         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name       | varchar(255)     | NO   |     | NULL    |                |
| country_id | int(11)          | NO   |     | NULL    |                |
+------------+------------------+------+-----+---------+----------------+
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's how to do a dynamic dropdown in Laravel:

You can see a demo of how it works here https://www.dronejobs.co/

Disclaimer: I didn't test this but it should work. Feel free to comment and I'll update ??

app/Http/Controllers/HomeController.php

<?php

namespace AppHttpControllers;

use App{Country, State};

class HomeController extends Controller
{
    public function index()
    {
        return view('home', [
            'countries' => Country::all(),
            'states' => State::all(),
        ]);
    }
}

resources/views/home.blade.php

<select name="country">
    @foreach ($countries as $country)
        <option value="{{ $country->id }}">{{ $country->name }}</option>
    @endforeach
</select>

<select name=“state”>
    @foreach ($states as $state)
        <option value="{{ $state->id }}">{{ $state->name }}</option>
    @endforeach
</select>

<script>
    $(function() {
        $('select[name=country]').change(function() {

            var url = '{{ url('country') }}' + $(this).val() + '/states/';

            $.get(url, function(data) {
                var select = $('form select[name= state]');

                select.empty();

                $.each(data,function(key, value) {
                    select.append('<option value=' + value.id + '>' + value.name + '</option>');
                });
            });
        });
    });
</script>

app/Country.php

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Country extends Model
{   
    public function states()
    {
        return $this->hasMany('AppState');
    }

app/State.php

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

Class State extends Model
{   
    public function country()
    {
        return $this->belongsTo('AppCountry');
    }

routes/web.php

Route::get('country/{country}/states', 'CountryController@getStates');

app/Http/Controllers/CountryController.php

<?php

namespace AppHttpControllers;

use AppCountry;

class CountryController extends Controller
{
    public function getStates(Country $country)
    {
        return $country->states()->select('id', 'name')->get();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...