【发布时间】:2018-06-04 13:12:50
【问题描述】:
I'm currently using Laravel and I want to have a dropdown box display category names from my database, but when selected the value it returns to the server should be a numerical value of the name selected which is also stored in the database .
像这样:
@foreach($categories as $category)
<option name="pid" value="$category->id" id="cname">{{$category->name}}</option>
@endforeach
值从我的控制器传递到 Blade 模板。如您所见,我希望它在下拉列表中显示类别名称(这很好),但是一旦选择并提交,我希望返回类别 ID。由于“值”属性返回值,我希望变量$category->id 作为“值”。我想在不使用 JavaScript 或 jQuery 的情况下做到这一点。仅使用 PHP。我将如何实现这一点,甚至有可能吗?
当我尝试使用 value="{{$category->id}}" 时,我收到 Laravel 错误:
违反完整性约束:1048 列 'parent_id' 不能为空
所以它似乎没有提交下拉列表的值。
这是我目前在 Blade 模板中使用的代码:
<form class="" action="{{route('createsubcategorypost')}}" method="post">
<div class="form-group">
<label for="cname">Sub-Category name:</label>
<input type="text" name="cname" value="" placeholder="Sub-Category Name" id="cname" class="form-control">
</div>
<div class="form-group">
<label for="pid">Parent ID</label>
<select class="form-control">
@foreach($categories as $category)
<option name="pid" value="{{$category->id}}" id="pid">{{$category->name}}</option>
@endforeach
</select>
</div>
<div class="form-group">
<center>
<button type="submit" name="button" class="btn btn-success">Create Sub-Category</button>
</center>
</div>
{{csrf_field()}}
</form>
这是我的控制器中的代码:
public function CreateSubCategoryPost(Request $request){
if ($request->cname == null) {
session()->flash('errormessage',' Invalid sub-category name.');
return redirect()->back();
}
$scc = SubCategory::where('name',$request->cname)->first();
if ($scc !== null) {
session()->flash('errormessage',' Sub-category with that name already exists.');
return redirect()->back();
}
$subCategory = new SubCategory;
$subCategory->name = $request->cname;
$subCategory->uniqueid = 'SCA'.str_random(28);
$subCategory->slug = str_slug($request->cname,'-');
$subCategory->parent_id = $request->pid;
$subCategory->save();
return redirect()->route('categories');
}
【问题讨论】:
标签: php html laravel bootstrap-4 blade