Mehdi Yaghoubi
Mehdi Yaghoubi

Reputation: 653

Deleting an Item from array of a table column in Laravel

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?

Upvotes: 0

Views: 389

Answers (1)

Foued MOUSSI
Foued MOUSSI

Reputation: 4813

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();
  }
}

Upvotes: 1

Related Questions