djhru
djhru

Reputation: 336

Delete image after upload new one

I'm working with laravel 5.4 I have a form which I can upload my logoimage and in update function I have this code:

//Save logo
         if ($request->hasFile('logo')) {
           $avatar = $request->file('logo');
           $filename = time() . '.' . $avatar->getClientOriginalExtension();
           $location = public_path('avatars/logos/');
           $request->file('logo')->move($location, $filename);
           $oldFilename = $general_Settings->logo;

           $general_Settings->logo = $filename;
           Storage::delete($oldFilename);
         }

         $general_Settings->save();

for updating my image which is work but as you see I have Storage::delete($oldFilename); this part doesn't work and just keep the old image.

what do you think is issue of that?

Upvotes: 0

Views: 1592

Answers (2)

djhru
djhru

Reputation: 336

Solved:

The issue was Filesystem.php I made my local root set to 'root' => public_path('avatars/'), and changed all my functions in my app because no way to save images in sub-folders and delete them just can save in sub-folders.

then my update function become like this:

 if ($request->hasFile('logo')) {
        $avatar = $request->file('logo');
        $filename = 'sitelogo' . '-' . time() . '.' . $avatar->getClientOriginalExtension();
        $location = public_path('avatars/');
        $request->file('logo')->move($location, $filename);


        $general_Settings->logo = $filename;
      }

      $general_Settings->save();

I hope this help someone.

Upvotes: 1

Sagar Gautam
Sagar Gautam

Reputation: 9389

Since, You have stored logo file name only not full path of file,

You need to give full path from public folder to delete image. Change delete line as:

if ($request->hasFile('logo')) {
       $avatar = $request->file('logo');
       $filename = time() . '.' . $avatar->getClientOriginalExtension();
       $location = public_path('avatars/logos/');
       $request->file('logo')->move($location, $filename);

       $oldFilename = $general_Settings->logo;
       $file_path = "avatars/logos/".$oldFilename;

       $general_Settings->logo = $filename;
       Storage::delete($file_path);
     }

     $general_Settings->save();

This might work.

Upvotes: 0

Related Questions