I have two tables named departments and designations. I want to show the designations depending on the department selected. But my code is not working, I looked for the solution for 3 days but failed.
Department Table:
id | department |
---|---|
1 | IT |
2 | Accounts |
Designation Table:
id | designation | department_id |
---|---|---|
1 | Manager | 1 |
2 | Manager | 2 |
Department Model:
public function designation(){
return $this->hasMany(Designation::class);
}
Designation Model:
public function department(){
return $this->belongsTo(Department::class);
}
Route:
Route::get('/getdesignation','EmployeeController@getdesignation');
});
Controller:
public function getdesignation(Request $request){
$data=Designation::select('designation','id')->where('department_id',$request->id)->get();
return response()->json($data);
}
Blade:
<select name="department_id" id="department_id" required>
<option value="" selected>Select one</option>
@foreach($departments as $row)
<option value="{{ $row->id }}">{{ $row->department }}</option>
@endforeach
</select>
<select name="designation_id" id="designation_id" required></select>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('change', '#department_id', function() {
var dpt_id = $(this).val();
if (dpt_id) {
$.ajax({
type: 'get',
url: '{!! URL::to('getdesignation') !!}',
data: {
'id': dpt_id
},
success: function(data) {
if (data) {
$('#designation_id').empty();
$('#designation_id').append(
'<option hidden>Select Designation</option>');
$.each(data, function(key, value) {
$('select[name="designation_id"]').append(
'<option value="' key '">' value
.designation '</option>');
});
} else {
$('#designation_id').empty();
}
}
});
} else {
$('#designation_id').empty();
}
});
});
</script>
Also when I update the data, how to select the old value?
CodePudding user response:
Actually,
var dpt_id = $(this).val();
Will return null as the element is a select input thus you will send department_id as null
Finally send null to request and get also null at response since null is not matched with any rows :)
So the first step is for you to get the value of the selected option by
var dpt_id = $(this).find(':selected').val()
It will return the value of the option which is selected
Secondly, Isn't it better to assign the designation id as option value instead the array index?
I assume you should use value.id
instead using key
I think it helps you. And let me know the updates!