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?

4
  • what is the field images store, a string like "p1.jpg" or a JSON array? Commented Feb 3, 2020 at 12:13
  • Just use an update query to overwrite the images column with the new array? Commented Feb 3, 2020 at 12:15
  • ["p1.jpg", "p2.jpg","p4.jpg","p9.jpg","p11.jpg", "p12.jpg","p13.jpg", "p14.jpg"] Commented Feb 3, 2020 at 12:16
  • already tested didn't work Commented Feb 3, 2020 at 12:33

1 Answer 1

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();
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

this return the index: foreach ($imgs as $v){ $position = array_search(request()->img, $v); } => 5 or ...
COuld you dump $imgs result and paste it here ?
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" } } }
yes. it worked. thank you Foued, you did great. it is the best solution in StackOverflow about deleting an item from an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.