In this shot, we go through how to delete files from your public directory. In our public directory, we have a folder called upload
. Within that folder, we have the test.png
file we want to delete.
We check if the file exists so that we don’t try to delete a file that doesn’t exist, resulting in errors.
We do this using the following:
File::exists(public_path('upload/test.png'))
We delete the file if it exists:
File::delete(public_path('upload/test.png'));
If the file doesn’t exist, you send a response. Here, we just dump:
dd('File does not exists.');
Here is the complete code block done in a DeleteController
:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use File;
class DeleteController extends Controller
{
/**
* Write code on Construct
*
* @return \Illuminate\Http\Response
*/
public function removeImage(Request $request)
{
if(File::exists(public_path('upload/test.png'))){
File::delete(public_path('upload/test.png'));
}else{
dd('File does not exists.');
}
}
}
RELATED TAGS
CONTRIBUTOR
View all Courses