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();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…