Как с помощью ajax Laravel вытащить данные взависимый select?
Есть форма с которой я отправляю запрос, и получаю данные. То есть я выбираю отдел и мне нужно что бы из бд подтянулся руководитель. Сейчас он тянет поле user_id, как сделать так чтобы он вытаскивал имя из таблицы user. Модель подразделения
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
Контролер запроса
class AjaxManager extends Controller
{
public function application($id){
$department = Department::where('id','=' ,$id)->get();
return response()->json($department, 200, [], JSON_UNESCAPED_UNICODE);
}
}
Вызов
<script>
(function ($) {
$('#form_application_create #department_id').change(function () {
var $this = $(this);
$.ajax({
type: 'POST',
url: '{{route('employee_selection.application.index')}}/ajax/' + $this.val(),
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
dataType: 'json',
data: {}
})
.done(function (department) {
$('#form_application_create #manager').empty();
department.forEach(function (department) {
$('#form_application_create #manager').append('<option value="' + department['user_id'] + '" data-percent=" ">' + department['user_id'] + '</option>');
})
})
.fail(function () {
console.log('error');
});
});
})(jQuery);
Ответы (1 шт):
Автор решения: Knyaz71
→ Ссылка
Если я правильно догадался то:
class AjaxManager extends Controller
{
public function application($id){
$department = Department::where('id','=' ,$id)->with(['user'])->get();
return response()->json($department, 200, [], JSON_UNESCAPED_UNICODE);
}
}
(function ($) {
$('#form_application_create #department_id').change(function () {
var $this = $(this);
$.ajax({
type: 'POST',
url: '{{route('employee_selection.application.index')}}/ajax/' + $this.val(),
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
dataType: 'json',
data: {}
})
.done(function (department) {
$('#form_application_create #manager').empty();
department.forEach(function (department) {
$('#form_application_create #manager').append('<option value="' + department['user_id'] + '" data-percent=" ">' + department['user']['name'] + '</option>');
})
})
.fail(function () {
console.log('error');
});
});
})(jQuery);