Мне нужно добавить динамический зависимый выпадающий список Laravel. Я не совсем понимаю..
В моей базе данных есть и категории, и их дети.
- Account_id = 0 => Категория
- Account_id = 1 => Подкатегория категории или подкатегории с id = 1
- Account_id = 2 => Подкатегория категории или подкатегории с id = 2
Это мой фактический код:
Метод:
public function index()
{
$categories = Account::where('account_id', '=', 0)->get();
$allCategories = Account::where('account_id', '=', 0)-
>pluck('account_name','id');
return view('Account.list',compact('categories', 'allCategories')); //
set the path of you templates file.
}
public function children(Request $request)
{
return Account::where('account_id', $request->account_id)->pluck('account_name', 'id');
}
Просмотр:
<div class="form-group">
{!! Form::label('account_id', 'Parent Category:')!!}
{!! Form::select('account_id', $allCategories, ['placeholder' =>
'Choose Category'])!!}
</div>
<div class="form-group">
{!! Form::label('children', 'Child category:')!!}
{!! Form::select('children', [], null, ['placeholder' => 'Choose child
category'])!!}
</div>
Маршрут:
Route::get('/categories', [
'uses' => 'AccountController@index',
'as' => 'categories'
]);
Route::get('/categories/children', [
'uses' => 'AccountController@children',
'as' => 'categories.children'
]);
JS:
<script>
$('#account_id').change(function(e) {
var parent = e.target.value;
$.get('/categories/children?account_id=' + account_id, function(data) {
$('#children').empty();
$.each(data, function(key, value) {
var option = $("<option></option>")
.attr("value", key)
.text(value);
$('#children').append(option);
});
});
});
</script>