sql >> Database teknologi >  >> RDS >> Mysql

Laravel dynamisk dropdown land og stat

Sådan laver du en dynamisk dropdown i Laravel:

Ansvarsfraskrivelse:Jeg testede ikke dette, men det burde virke. Kommenter gerne, så opdaterer jeg 🙏

app/Http/Controllers/HomeController.php

<?php

namespace App\Http\Controllers;

use App\{Country, State};

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

ressourcer/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 Illuminate\Database\Eloquent\Model;

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

app/State.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

routes/web.php

Route::get('country/{country}/states', '[email protected]');

app/Http/Controllers/CountryController.php

<?php

namespace App\Http\Controllers;

use App\Country;

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


  1. Hvordan tager man MySQL database backup ved hjælp af MySQL Workbench?

  2. download værdier af sql-tabellen til offline genbrug

  3. Adjacency List Model vs Nested Set Model for MySQL hierarkiske data?

  4. Hvordan udfører man en forespørgsel, der er gemt i en tabelkolonne MySQL?