Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.4: how to delete a file stored in storage/app

I want to delete a file that is stored in storage/app/myfolder/file.jpg. I have tried the following codes but none of this works:

use File     $file_path = url().'/storage/app/jobseekers_cvs/'.$filename; unlink($file_path); 

and

use File $file_path = public_path().'/storage/app/myfolder/'.$filename; unlink($file_path); 

and

use File $file_path = app_path().'/storage/app/myfolder/'.$filename; unlink($file_path); 

and also,

File::Delete('/storage/app/myfolder/'.$filename); 

Please help.

like image 308
Ajmal Razeel Avatar asked Jul 12 '17 18:07

Ajmal Razeel


People also ask

How do I delete files from storage in Laravel?

One way to delete a file from the public directory in Laravel is to use the Storage facade. To delete a file, you will need to follow the following steps: Step 1: Check to ensure that the folder and file exist. Step 2: Delete the required file.

How do I delete files from storage?

Tap and hold a file to select it, then tap the trash can icon, the remove button or the delete button to get rid of it.

How do I delete files after downloading in Laravel?

Just place it in the controller instead of the app/start/global. php." DeleteFileAfterSend(true) works great on Laravel 5.3 as well. Although the documentation doesn't state anything about it, you can still use it.


2 Answers

You could either user Laravels facade Storage like this:

Storage::delete($file); 

or you could use this:

unlink(storage_path('app/folder/'.$file)); 

If you want to delete a directory you could use this:

rmdir(storage_path('app/folder/'.$folder); 

One important part to mention is that you should first check wether the file or directory exists or not.

So if you want to delete a file you should probably do this:

if(is_file($file)) {     // 1. possibility     Storage::delete($file);     // 2. possibility     unlink(storage_path('app/folder/'.$file)); } else {     echo "File does not exist"; } 

And if you want to check wether it is a directory do this:

if(is_dir($file)) {     // 1. possibility     Storage::delete($folder);     // 2. possibility     unlink(storage_path('app/folder/'.$folder));     // 3. possibility     rmdir(storage_path('app/folder/'.$folder)); } else {     echo "Directory does not exist"; } 
like image 176
utdev Avatar answered Sep 18 '22 09:09

utdev


Use storage

//demo  use Illuminate\Support\Facades\Storage;  Storage::delete($filename); 

Another way,

unlink(storage_path('app/folder/'.$filename)); 
like image 27
Minar Mnr Avatar answered Sep 19 '22 09:09

Minar Mnr