laravel 我想在更新新图像的同时删除存储的图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44880538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:15:04  来源:igfitidea点击:

I want to delete the stored image while update new image

laravellumen

提问by Krunal

I want to delete the stored image while update new image

我想在更新新图像的同时删除存储的图像

public function update($id)
    {
        $users = AdminLogin::find($id);

        if(Input::hasFile('image_file'))
        {
            $file = Input::file('image_file');
            $name = time() . '-' . $file->getClientOriginalName();
            $file = $file->move(('uploads/images'), $name);
            $users->image_file= $name;
        }
        $users->save();
        return response()->json($users);
    }

回答by Jahid Mahmud

You can write this. This will solve your problem

你可以写这个。这将解决您的问题

public function update($id)
{
    $users = AdminLogin::find($id);

    if(Input::hasFile('image_file'))
    {
        $usersImage = public_path("uploads/images/{$users->image_file}"); // get previous image from folder
        if (File::exists($usersImage)) { // unlink or remove previous image from folder
            unlink($usersImage);
        }
        $file = Input::file('image_file');
        $name = time() . '-' . $file->getClientOriginalName();
        $file = $file->move(('uploads/images'), $name);
        $users->image_file= $name;
    }
    $users->save();
    return response()->json($users);
}

This will delete the previous image and update the new image

这将删除以前的图像并更新新图像

回答by Mohsin Khan

Well, the answer is technically incorrect. What if the save operation fails, since you have deleted that image the current record will not have an image anymore. So to overcome this problem you can adjust your code like:

好吧,答案在技术上是不正确的。如果保存操作失败怎么办,因为您已删除该图像,当前记录将不再有图像。所以为了克服这个问题,你可以调整你的代码,如:

    if(Input::hasFile('image_file'))
        {

            $file = Input::file('image_file');
            $name = time() . '-' . $file->getClientOriginalName();
            $file = $file->move(('uploads/images'), $name);
            $users->image_file= $name;
        }
        $users->save();
        if(Input::hasFile('image_file'))
           {
               $usersImage = public_path("uploads/images/{$users->image_file}"); // get previous image from folder
               if (File::exists($usersImage)) { // unlink or remove previous image from folder
                  unlink($usersImage);
               }
           }