我在Laravel中检索数据并使用它来检查复选框时遇到问题。我希望在打开编辑页面时根据数据库上的记录检查复选框。
编辑视图/刀片
@php
$productstatus = json_decode($product-\>status);
@endphp
<div>
<label for="status" class="control-label col-sm-2">Product Status</label>
@foreach($status as $status)
<input type="checkbox" name="status[]" value="{{$status->status}}" @if(in_array($status, $productstatus)) checked @endif> <label>{{$status->status}}</label>
@endforeach
</div>
<div class="clearfix"></div>
字符串
控制器
public function edit(Product $product)
{
$countries = Country::all();
$status = Status::all();
$allStatus = Product::pluck('status')->toArray();
return view('products.edit',
['product' => $product, 'countries' => $countries, 'status' => $status, 'allStatus' => $allStatus]);
}
public function update(Request $request, $id)
{
$data = $request->validate([
'name' => 'required',
'qty' => 'required|numeric',
'price' => 'required|decimal:0,2',
'category' => 'required',
'country' => 'required',
'status' => 'nullable',
'description' => 'nullable'
]);
$product = product::where('id', $id)
->update([
'name' => $request->name,
'qty' => $request->qty,
'price' => $request->price,
'category' => $request->category,
'country' => $request->country,
'status' => json_encode($request->input('status')),
'description' => $request->description
]);
return redirect(route('product.index'))->with('success', 'Product has been updated Successfully!');
}
型
I want the tickboxes to be ticked based on the values when the edit page is loaded
Here is the array of strings in the database的
我试图在将字符串与值进行比较之前将其更改为数组,但无济于事。
2条答案
按热度按时间zxlwwiss1#
在视图文件中,您将对象
$status
与数组$productstatus
进行比较。这将无法正常工作。您应该将$status
对象的status
属性与$productstatus
数组进行比较。字符串
在此代码中,
@if(in_array($status->status, $productstatus)) checked @endif
检查$status
对象的status
属性是否在$productstatus
数组中。如果是,则将checked
属性添加到复选框输入。kxeu7u2r2#
您在指定的程式码行中有错误。
转换此
字符串
到
型
然后此复选框html
型
到
型