Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

laravel
php
communitycreator

How to delete a file from public directory using the File facade

Chinweuba Elijah Azubuike

Overview

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.

Step 1

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'))

Step 2

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

laravel
php
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring