Meeraj Adhikari
Meeraj Adhikari

Reputation: 391

Old File from storage is not being deleted on update Laravel

I am trying to delete the existing image from the storage while the new image is being updated. But everytime the new image is inserted retaining the previous ones.

When I dd the image from database to unlink, I get full url i.e.

http://127.0.0.1:8000/teacger-image/1598097262-85508.jpg

While only teacher-image/1598097262-85508.jpg has been stored in the database.

Function to delete the image

public function deleteImageFromStorage($value)
{
    if (!empty($value)) {
        File::delete('public/' . $value);
    }
}

I have called the method in the controller when there is image posted during update.

update method includes

 if ($request->hasFile('image')) {
            $teacher->deleteImageFromStorage($teacher->image);
            $file = $request->file('image');
            $filename =  time() . '-' . mt_rand(0, 100000) . '.' . $file->getClientOriginalExtension();
            $path = $file->storeAs('teacher-image', $filename);
            $teacher->image = $path;
        }

Also I have used Storage::delete() and unlink as well but none of them seem to work.

help

Upvotes: 0

Views: 801

Answers (3)

Meeraj Adhikari
Meeraj Adhikari

Reputation: 391

I had to do this to solve my problem. The url was being taken by the configuration set on filesystems.php under config file.

public function deleteImageFromStorage($value)
{
    $path_explode = explode('/', (parse_url($value))['path']); //breaking the full url 
    $path_array = [];
    array_push($path_array, $path_explode[2], $path_explode[3]); // storing the value of path_explode 2 and 3 in path_array array
    $old_image = implode('/', $path_array);

    if ($old_image) {
        Storage::delete($old_image);
    }
}

If someone goes through the same problem in the future, this might be helpful.

Upvotes: 0

Adrian Edy Pratama
Adrian Edy Pratama

Reputation: 4051

Try change your deleteImageFromStorage method to this:

public function deleteImageFromStorage($value)
{
    if (!empty($value)) {
        File::delete(public_path($value));
    }
}

Upvotes: 0

Brinley
Brinley

Reputation: 100

This is how I've been deleting files in Laravel.

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ImagesController extends Controller
{
    public function deleteImageFromStorage($value)
    {
        if ( file_exists( storage_path($value) ) ) {
            Storage::delete($value);
        }
    }
}

Make sure to use Illuminate\Support\Facades\Storage.

Upvotes: 1

Related Questions