我需要添加一个Laravel动态相关下拉列表。我很困惑.. 在我的数据库中,我同时拥有类别及其子类别。
这是我的实际代码:
方法:
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>
答案 0 :(得分:1)
首先尝试创建新的route
Route::post('subchildren/youcontroller', [
'as' => 'children.categories',
'uses' => 'youUrlController\yourController@childrenCategory',
]);
下一步创建route
转到controller
创建新的method
public function childrenCategory(Request $request)
{
try {
$subCategory= subCategory::where('category_id', $request->nameSelectCategoryinYourView)->get();
return response()->json(['subCategory' => $subCategory], 200);
} catch (Exception $e) {
return response()->json(['error' => 'Error'], 403);
}
}
下一步view
<div class="form-group m-b-40">
<select name="subCategory" class="form-control p-0" id='subCategory'></select>
</div>
下一步javascript
jQuery(document).ready(function($) {
$('#FirstSelect').change(function () {
$('#subCategory').empty();
var Category = $(this).val();
datos = {
tipo : Category
},
$.ajax({
url: '{{ route('children.categories') }}',
type: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: datos,
success: function (argument) {
arreglo = {id:"a", tipo:""};
argument.detalles.unshift(arreglo);
$.each(argument.subCategory, function(index, el) {
var opcion = '<option value="'+ el.id +'">'+ el.subCategoryName+'</option>';
$('#subCategory').append( opcion );
});
}
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
})
});
});