我如何从数组中的图像名称中删除一个图像的名称?

时间:2017-08-09 22:09:29

标签: php laravel laravel-5.3 delete-row

我在阵列中有多个图像,如:

["1.jpg","2.jpg"]

我需要从db中的数组中的图像名称中删除一个图像的名称, 这是我的表格,以显示和删除提交:

@foreach(json_decode($post->images ,true) as $images)
<div class="col-lg-2 col-md-2 col-sm-2">
    <div class="portfolio-box">
        <img src="public/img/offers/{{ $images }}" class="img-responsive"alt="">
        <div class="portfolio-box-caption">
            <div class="portfolio-box-caption-content">
                <form action="images/{{ $images }}/delete" method="get">

                    {!! csrf_field() !!}

                    <input type="submit" class="btn btn-danger" value="Delete">

                </form>
            </div>
        </div>
    </div>
</div>
@endforeach

这是我的路线:

    Route::get('images/{images}/delete','DashboardController@deleteimg');

我在Controller中做了什么?

1 个答案:

答案 0 :(得分:1)

在表单中传递帖子ID

@foreach(json_decode($post->images ,true) as $images)
 <div class="col-lg-2 col-md-2 col-sm-2">
   <div class="portfolio-box">
    <img src="public/img/offers/{{ $images }}" class="img-responsive"alt="">
    <div class="portfolio-box-caption">
        <div class="portfolio-box-caption-content">
            <form action="images/{{ $images }}/delete" method="get">

                {!! csrf_field() !!}
                <input type="hidden"  name="post_id" value="{{$post->id}}"/>
                <input type="submit" class="btn btn-danger" value="Delete">

            </form>
         </div>
        </div>
      </div>
     </div>
@endforeach

在控制器中

public function deleteimg($image,Request $req){
   $post=Post::find($req['post_id']);
   $images=json_decode($post->images);
   $_image=[];
   $_image[]=$image;
   $post->images=json_encode(array_values(array_diff($images,$_image)));
   $post->save();
   return redirect()->back();
}

OR

public function deleteimg($image,Request $req){
   $post=Post::find($req['post_id']);
   $images=json_decode($post->images);
   unset($images[$image]);
   $post->images=json_encode(array_values(images));
   $post->save();
   return redirect()->back();
}