How To Delete File From Public / Storage Folder In Laravel

In this example we will see how to delete file from public / storage folder in laravel 6/7/8. So, here I will explain how to delete image from public / storage folder using laravel file system and php function file_exists() and unlink().

Many time we required to remove file from folder in laravel 6, laravel 7 and laravel 8 application. laravel store file in public folder and storage folder, so most of the cases you simply need to delete file from public folder or storage folder. In laravel 6/7/8 provide Storage and File facads for remove file / image from public / storage folder.

Images or file uploads are comman functionalites in web developing, many time we required to delete images or file from our database but those files are still saved in our laravel storage function, if you are not take any action then it will be occupies more space. So, we need to remove it manually or we can remove via laravel function or core php function.

Using Storage System

First we are delete image using laravel Storage function in storage folder. 

public function removeImage()
{  
  if(\Storage::exists('upload/storage_img.png')){
    \Storage::delete('upload/storage_img.png');
  }else{
    dd('File not found.');
  }
}

 

 

Using File System

Now, we are delete image using laravel File function from public folder.

public function removeImage()
{  
  if(\File::exists(public_path('upload/public_img.png'))){
    \File::delete(public_path('upload/public_img.png'));
  }else{
    dd('File not found');
  }
}

 

Using PHP

In PHP fisrt we check file is exist or not then unlink file path using unlink() PHP function.

public function removeImage()
{  
    if(file_exists(public_path('upload/img.png'))){
      unlink(public_path('upload/img.png'));
    }else{
      dd('File not found');
    }
}

 


You might also like :

RECOMMENDED POSTS

FEATURE POSTS