I have a problem retrieving data and using it to check checkboxes in Laravel. I want the checkboxes to be checked based on the records on the database when the edit pages are opened.
Edit view/blade
@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>
Controller
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
I tried to change the string into arrays back before comparing it to the values but to no avail.
>Solution :
In your view file, you compare an object $status with an array $productstatus. This will not work as expected. You should compare the status property of the $status object with the $productstatus array.
@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->status, $productstatus)) checked @endif> <label>{{$status->status}}</label>
@endforeach
</div>
<div class="clearfix"></div>
In this code, @if(in_array($status->status, $productstatus)) checked @endif checks if the status property of the $status object is in the $productstatus array. It adds the checked attribute to the checkbox input if it is.