laravel 如何先删除旧头像再上传新头像?

lf5gs5x2  于 2023-05-19  发布在  其他
关注(0)|答案(2)|浏览(145)

这是正确的做法吗?

public function uploadAvatar(Request $request)
    {
        $request->validate([
            'image' => 'image|file|mimes:jpeg,png,jpg|max:1500|dimensions:max_width=800,max_height=800'
        ] , [
            'image.image' => 'Must be an :attribute!',
            'image.max' => 'The :attribute may not be greater than :max kilobytes.',
            'image.mimes' => 'The :attribute must be a file of type: :values.',
            'image.dimensions' => 'The :attribute has invalid image dimensions.',
        ]);

        if (auth()->user()->avatar) {
            Storage::delete(public_path('user-images/' . auth()->user()->avatar));
        }

        if($request->hasFile('image'))
        {
            $filename = $request->image->getClientOriginalName();
            $request->image->storeAs('user-images', $filename, 'public');
            auth()->user()->update(['avatar' => $filename]);
            return redirect()->back()->with('successUploadImg', 'Profile picture updated successfully!');
        }
    }

谢谢你帮忙!
注意:我使用Storage:Link。我在想我走错路了

cig3rfwq

cig3rfwq1#

您的删除也应该在您检查是否有任何图像正在上传的条件内。现在,即使你不上传一个头像,它也会删除旧的。
验证码:

if($request->hasFile('image')) { 
   Storage::delete(public_path('user-images/' . auth()->user()->avatar));
   // Rest of the logic
}
bmp9r5qi

bmp9r5qi2#

使用取消链接功能从文件夹中删除文件

if (auth()->user()->avatar) {
     $image_path = public_path('user-images/' . auth()->user()->avatar)
     unlink($image_path)
}

相关问题