open your browser network tools
- Is the request being sent after changing the first dropdown?
- does the request contain the correct URL and the selection value made
- do you get a 200 reply?
- does the reply contain the json you expected?
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
How to Create Dynamic Dependent Dropdown in Laravel 8 ?
basically, I want to show program data in dropdown based on selected mode. With the code that I've made below, I can already display program data in the dropdown when I select mode 1 or active online. But when I select mode 2 or Full Hybrid, the data in the dropdown doesn't appear.
Route
Route::post('/programs', function (Request $request) {
$programs = App\Models\Program::where('mode',$request->mode_id)
->with('programs')
->get();
return response()->json([
'programs' => $programs
]);
})->name('program');
Blade
<meta name="csrf-token" content="{{ csrf_token() }}">
...
...
...
<div class="form-group row">
<div class="col-md-6 mb-3">
<label for="mode">Mode</label>
<select class="custom-select @error('mode') is-invalid @enderror" id="mode" name="mode">
<option hidden>Choose Program</option>
<option value="1">Active Online</option>
<option value="2">Full Hybrid</option>
</select>
@error('mode')
<div class="invalid-feedback">
{{$message}}
</div>
@enderror
</div>
<div class="col-md-6 mb-3">
<label for="pro">Program</label>
<select class="custom-select @error('program_id') is-invalid @enderror" id="program" name="program_id">
</select>
@error('program_id')
<div class="invalid-feedback">
{{$message}}
</div>
@enderror
</div>
</div>
...
...
...
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$('select[name="mode"]').on('change',function(e) {
var mode_id = e.target.value;
$.ajax({
url:"{{ route('program') }}",
type:"POST",
data: {
mode_id: mode_id
},
success:function (data) {
// console.log(mode_id);
$('#program').empty();
$.each(data.programs[0].programs,function(index,program){
$('#program').append('<option value="'+program.id+'">'+program.nama+'</option>');
})
}
})
});
});
</script>
Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Program extends Model
{
use HasFactory;
use SoftDeletes;
protected $table = 'programs';
protected $fillable = ['nama', 'department', 'mode', 'enabled'];
protected $dates = ['updated_at','created_at'];
public function programs()
{
return $this->hasMany('App\Models\Program', 'mode');
}
}
What is the correct way to create a Dynamic Dependent Dropdown in Laravel 8 ? thank you
I have successfully solved this question by following the tutorial in this article.
Please or to participate in this conversation.