0

There is a Posts table that has a column named images. in images I store data as JSON array as:

["p1.jpg", "p2.jpg","p4.jpg","p9.jpg","p11.jpg", "p12.jpg","p13.jpg", "p14.jpg"];

I want to delete one of these images by ajax. I send the id and image by ajax and get that id and image in the controller correctly:

  public function remove() {

$imgs = Image::where('id', request()->id)->pluck('images');
return $imgs;
  }

reults in console:
[Array(8)]
0: (8) ["p1.jpg", "p2.jpg", "p4.jpg", "p9.jpg", "p11.jpg", "p12.jpg", "p13.jpg", "p14.jpg"]
length: 1
__proto__: Array(0)

also, I get the image name by request()->img from ajax.

$image = request()->img; => p12.jpg

How I can delete the $image from $images array?

Mehdi Yaghoubi
  • 561
  • 3
  • 8
  • 24

1 Answers1

1

First You may cast images attr to array in your Image model

//App\Image
protected $casts = [
        'images' => 'array'
];

Then in your remove function :

public function remove() {
  if(request()->id && request()->img) {
     $imgModel = Image::findOrFail(request()->id);
     $imgs = $imgModel->images;

     // find request()->img position inside imgs array
     $position = array_search(request()->img, $imgs);

     // delete request()->img
     unset($imgs[$position]);

     $imgModel->images = array_values($imgs);
     $imgModel->save();
  }
}
Foued MOUSSI
  • 4,643
  • 3
  • 19
  • 39
  • this return the index: foreach ($imgs as $v){ $position = array_search(request()->img, $v); } => 5 or ... – Mehdi Yaghoubi Feb 03 '20 at 12:49
  • COuld you dump $imgs result and paste it here ? – Foued MOUSSI Feb 03 '20 at 12:57
  • object(Illuminate\Support\Collection)#294 (1) { ["items":protected]=> array(1) { [0]=> array(8) { [0]=> string(6) "p1.jpg" [1]=> string(6) "p2.jpg" [2]=> string(6) "p4.jpg" [3]=> string(6) "p9.jpg" [4]=> string(7) "p11.jpg" [5]=> string(7) "p12.jpg" [6]=> string(7) "p13.jpg" [7]=> string(7) "p14.jpg" } } } – Mehdi Yaghoubi Feb 03 '20 at 13:05
  • yes. it worked. thank you **Foued**, you did great. it is the best solution in StackOverflow about deleting an item from an array. – Mehdi Yaghoubi Feb 03 '20 at 13:39