How to Delete file from public folder – Laravel 9

If you allow the users to upload profile,  product, items photos, or documents and during updating file process if you are not deleting the previously uploaded file then in that case files keep getting stored and occupying space on the server.

In this tutorial, I am only covering file deletion not file upload. You can view this tutorial for file upload in Laravel.

How to Delete file from public folder - Laravel 9


Contents

  1. File stored
  2. Controller
  3. Route
  4. View
  5. Output
  6. Conclusion

1. File stored

I created files folder in public folder to store some files.

File stored in public folder - Laravel

 


2. Controller

  • Create PagesController controller.
php artisan make:controller PagesController
  • Import File for file deletion – use Illuminate\Support\Facades\File;.
  • Create 2 methods –
    • index – Store file path in $files Array. Assign $files to $data['files'].

Load index view and pass $data Array.

    • deleteFile – Using this method delete a file.

Read POST filepath and assign it to $filepath. Check if $filepath exists or not using File::exists().

To delete a file using –

File::delete($filepath);

Here, pass $filepath to File::delete().

If a file is successfully deleted then assign success message to Session::flash. Similarly, assign the failed message to Session::flash.

Completed Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Session;

class PagesController extends Controller {

   public function index() {

      ## Files list
      $files[] = 'files/file1.jpg';
      $files[] = 'files/file2.jpg';
      $files[] = 'files/file3.jpg';
      $files[] = 'files/file4.jpg';
      $files[] = 'files/file5.jpg';
      $files[] = 'files/file6.jpg';
      $files[] = 'files/file7.jpg';
      $files[] = 'files/file8.jpg';

      $data['files'] = $files;

      return view('deletefile',$data);
   }

   public function deleteFile(Request $request){

      ## Read file path
      $filepath = $request->post('filepath');

      ## Check file exists
      if (File::exists($filepath)) {

         ## Delete file
         File::delete($filepath);

         Session::flash('message','Deleted Successfully.');
         Session::flash('alert-class', 'alert-success');
      }else{
         Session::flash('message','File not exists.');
         Session::flash('alert-class', 'alert-danger');
      }

      return redirect('/');
   }
}

3. Route

  • Open routes/web.php file.
  • Define 2 routes –
    • / – Load index view.
    • /deletefile – This is POST type route to delete file.
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PagesController;

Route::get('/', [PagesController::class, 'index']); 
Route::post('/deleteFile', [PagesController::class, 'deleteFile'])->name('deleteFile');

4. View

Create index.blade.php file in resources/views/.

Display file deletion success or failed message using Bootstrap alert if Session is been set.

Loop on $files Array to display image file preview with delete button.

For delete create <form method='post' action="{{ route('deleteFile') }}">. In the <form > create a hidden field to store file path and a submit button.

Completed Code

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>How to Delete file from public folder - Laravel 9</title>

  <!-- CSS only -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" >
</head>
<body>

  <div class="container mt-5">
     <div class="row">
         <!-- Alert message (start) -->
         @if(Session::has('message'))
         <div class="alert {{ Session::get('alert-class') }}">
            {{ Session::get('message') }}
         </div>
         @endif 
         <!-- Alert message (end) -->

         @foreach($files as $file)

            @if(File::exists(public_path($file)))
                <div class="col-md-3 mb-2">
                    <img src="{{ asset($file) }}" width='200px' height='200px'> <br>
                    <form method='post' action="{{ route('deleteFile') }}">
                       @csrf
                       <input type="hidden" name="filepath" value="{{ $file }}">
                       <input type="submit" class="btn btn-danger" name="btnsubmit" value="Delete">
                    </form>
                </div>
            @endif
         @endforeach
     </div>
   </div>
</body>
</html>

5. Output

View Output


6. Conclusion

Use the above code to delete the existing files and make sure to check if file exists before executing the delete script.

In the example, I am deleting image files but you can similarly, delete other files.

If you are on Laravel 8 you can use the same code for file deletion.

If you found this tutorial helpful then don't forget to share.

Leave a Comment