I have a problem in retrieving datas and using it to check checkboxes in Laravel. I want that when the edit pages are opened, the checkboxes will be checked based on the records on the database.
Edit view page:
@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 Page:
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 that the tickboxes are ticked based on the values when the edit page is loaded
Here is the array of strings in the database
Thank you for helping!
I tried to change the string into arrays back before trying to compare it to the values, but to no avail.
2
Answers
In your view file, you compare an object
$status
with an array$productstatus
. This will not work as expected. You should compare thestatus
property of the$status
object with the$productstatus
array.In this code,
@if(in_array($status->status, $productstatus)) checked @endif
checks if thestatus
property of the$status
object is in the$productstatus
array. It adds thechecked
attribute to the checkbox input if it is.You have an error in the given line of code.
Convert this
To
Then this checkbox html
To
The in_array() function searches an array for a specific value and you are passing both of the arrays to the in_array function.