In this article, we will see how to delete files from the public folder in laravel 9. Here, we will learn how to delete or remove files and images from the public and storage folder in Laravel.
You can make use of the File facade class. To work with File facade you need to include the class as shown below :
use Illuminate\Support\Facades\File;
Now, we are deleting images using the laravel File function from the public folder.
public function removeImage()
{
if(\File::exists(public_path('upload/my_image.png'))){
\File::delete(public_path('upload/my_image.png'));
}else{
dd('File not found');
}
}
The delete
method accepts a single filename or an array of files to delete
use Illuminate\Support\Facades\Storage;
Storage::delete('file.jpg');
Storage::delete(['file.jpg', 'file2.jpg']);
Using unlink() method in php :
public function image() {
if (file_exists(public_path('upload/my_image.jpg'))){
$filedeleted = unlink(public_path('upload/my_image.jpg'));
if ($filedeleted) {
echo "File deleted";
}
} else {
echo 'File not found';
}
}