Ajax 从Laravel中的表列数组中删除项

Ajax 从Laravel中的表列数组中删除项,ajax,laravel,Ajax,Laravel,有一个Posts表,它有一个名为images的列。在图像中,我将数据存储为JSON数组,如下所示: ["p1.jpg", "p2.jpg","p4.jpg","p9.jpg","p11.jpg", "p12.jpg","p13.jpg", "p14.jpg"]; 我想通过ajax删除其中一个图像。我通过ajax发送id和图像,并在控制器中正确获取该id和图像: public function remove() { $imgs = Image::where('id', request()-

有一个Posts表,它有一个名为images的列。在图像中,我将数据存储为JSON数组,如下所示:

["p1.jpg", "p2.jpg","p4.jpg","p9.jpg","p11.jpg", "p12.jpg","p13.jpg", "p14.jpg"];
我想通过ajax删除其中一个图像。我通过ajax发送id和图像,并在控制器中正确获取该id和图像:

  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)
此外,我还通过请求()从ajax获得图像名->img

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

如何从$images数组中删除$image?

首先,您可以将images
attr
投射到图像模型中的数组中

//App\Image
protected $casts = [
        'images' => 'array'
];
然后在删除函数中:

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

什么是字段
images
store,类似
“p1.jpg”
的字符串还是JSON数组?只需使用更新查询就可以用新数组覆盖
images
列了?[“p1.jpg”、“p2.jpg”、“p4.jpg”、“p9.jpg”、“p11.jpg”、“p12.jpg”、“p13.jpg”、“p14.jpg”]已经测试过,但没有成功返回索引:foreach($imgs as$v){$position=array_search(request()->img,$v);}=>5或者…您可以转储$imgs结果并将其粘贴到这里吗?object(light\Support\Collection){[“items”:protected]=>array(1){[0]=>array(8){[0]=>string(6)“p1.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”}}}}是的。这很有效。谢谢你,你做得很好。这是StackOverflow中关于从数组中删除项的最佳解决方案。