Derick T.
Derick T.

Reputation: 77

Laravel 8 : Storage::delete (file) return false

Since yesterday I cannot delete a file from the folder This my code in the controller. ​ public function update_avatar(Request $request) {

    // Handle the user upload of avatar
    if ($request->hasfile('avatar')) {
        $avatar = $request->file('avatar');
        $filename = time() . '.' . $avatar->getClientOriginalExtension();
        if (auth()->user()->avatar) {
            // dd('/uploads/avatars/'. auth()->user()->avatar);
            Storage::delete('/uploads/avatars/'. auth()->user()->avatar);
            //dd(Storage::delete('/uploads/avatars/'. auth()->user()->avatar));
        }
        Image::make($avatar)->resize(500, 500)->save(public_path('/uploads/avatars/' . $filename));

        $user = Auth::user();
        $user->avatar = $filename;
        $user->save();
    }

    return view('profile', array('user' => Auth::user()) );

}

which does not delete the file in the folder, after debugging the method

dd('/uploads/avatars/'. auth()->user()->avatar); ​

i get the file correctly, but when I debug on

dd(Storage::delete('/uploads/avatars/'. auth()->user()->avatar)); ​

the result is FALSE

ps: Im using laravel 8

Upvotes: 2

Views: 15789

Answers (2)

Showkii Paa
Showkii Paa

Reputation: 101

DO this .

       if (Storage::exists('public'.$slider->image)) {
            Storage::delete('public'.$slider->image);
        }

Store method

        $image = Storage::disk('public')->put('admin/slider/', $request->image);
        $image = basename($image);
        $slider->image = '/admin/slider/' . $image;

save image using storage method in Database.
enter image description here

Upvotes: 0

bhucho
bhucho

Reputation: 3420

At first you are doing Storage::delete('/uploads/avatars/'. auth()->user()->avatar); so by default if you have not changed anything, the disk is set to local,

You can check it from your config/filesystems.php(Showing here from laravel github official repo (https://github.com/laravel/laravel/blob/8.x/config/filesystems.php#L44))

So if you select, Storage::disk('public')->delete($filename);, it would select the disk for public with path, app/public, even you can add it manually(I have not tested this method so can't guarantee its success.)

Second, if you use File, As you can see from https://github.com/laravel/framework/blob/8.x/src/Illuminate/Filesystem/Filesystem.php#L262, it basically calls unlink() method of php. Basically both of them call the delete method in Illuminate/Filesystem/Filesystem, but passing the path & methods of calling are different.

So you can use either,

  • use Illuminate\Support\Facades\File; File::delete($filename);
  • use IIlluminate\Support\Facades\Storage Storage::disk('public')->delete($filename); (on github)
  • unlink() from php

Upvotes: 8

Related Questions