I want to delete JSON from database but I can't
My delete function in controller:
public function deletephoto($id)
{
$product = $this->productRepository->findWithoutFail($id);
$photo = json_decode($product->photo_list,true);
$photos = $photo[$id-1];
unset($photos);
$product->save();
Flash::success('Photo deleted successfully.');
return back();
}
UPDATE Here my edit controller:
public function edit($id)
{
$product = $this->productRepository->findWithoutFail($id);
$store = Store::pluck('name', 'id')->all();
$photo = json_decode($product->photo_list);
//dd($photo);
$category = Category::pluck('name','id')->all();
if (empty($product)) {
Flash::error('Product not found');
return redirect(route('products.index'));
}
return view('products.edit',compact('product','store','category','photo'));
}
Here my view blade.php. I'm using button to delete it.
@foreach($photo as $pro)
<div style="margin-right:10px" class="form-group col-sm-1">
<p><img src="{{ env('FRONTEND_URL') . "/img/products/$product->id/$pro->name"}}" width="100" height="100"/></p>
<a href="{!! route('products.deletephoto', [$pro->id]) !!}" class='btn btn-default btn-xs' onclick="return confirm('Are you sure?')">Delete</a>
</div>
@endforeach
I clik my button delete but it doesn't work.
LASTEST UPDATE
My Delete Function
public function deletephoto($productid,$photoid)
{
$product = $this->productRepository->findWithoutFail($productid);
$photo = json_decode($product->photo_list,true);
foreach($photo as $key => $value) {
if($value['id'] == $photoid) {
unset($photo[$key]);
}
}
return back();
}
my view blade.php
@foreach($photo as $pro)
<div style="margin-right:10px" class="form-group col-sm-1">
<p><img src="{{ env('FRONTEND_URL') . "/img/products/$product->id/$pro->name"}}" width="100" height="100"/></p>
<a href="{!! route('products.deletephoto', [$product->id,$pro->id]) !!}" class='btn btn-default btn-xs' onclick="return confirm('Are you sure?')">Delete</a>
</div>
@endforeach
I use that code but it doesnt work too...
Currently you are getting photo_list
column using $id
and trying to remove it using the same $id
that's why it is not working. Suppose $id
is 23, then you don't have 23 id in your json array of photo_list
Now if you want to remove en element you need to have id
of single a image, using that id
you can remove like:
To remove key from all array
foreach($photo as $key => $value) {
if($value['id'] == '1') { // assumed 1 to be removed
unset($photo[$key]);
}
}
if you want to remove whole JSON, you can update that photo_list
column's value as NULL
EDIT
please check the below example:
$photo ='[{"id": "1","name": "test"},{"id": "2","name": "test"}]';
$photo_obj = json_decode($photo,true); // to get array
$result =[];
foreach($photo_obj as $key => $value) {
if($value['id'] != '1') { // assumed id = 1 to be removed
$result[] = $value;
}
}
print_r(json_encode($result));