Search code examples
phplaravelimageunlink

How do I remove my image from images folder in laravel?


In my edit detail page there is an image field, I want that when i upload new image old photo will remove from images folder and new photo will upload and if i do not upload pic than during submit no error will generate

here is my image upload code

$file = $request->file('file');
$name = time() . $file->getClientOriginalName();
$file->move('uploads/images', $name);
$employee->file = $name;
$employee->save();

How can I unlink it?


Solution

  • If you’re updating a model, you can delete the old file and upload the new one if one is provided:

    if ($request->hasFile('file')) {
        Storage::delete($employee->file); // If $file is path to old image
    
        $employee->file = $request->file('file')->store('name-of-folder');
    }