delete the previous image from the folder when updated by new image in Laravel

Delete the previous image from the folder when updated by new image in Laravel

Today, I will give you an example of “How to Delete the previous image from the folder when updated by a new image in Laravel”, So you can easily apply it with your laravel 5, laravel 6, laravel 7, laravel 8, and Laravel 9 application.

First, what we’re doing here, This is the example :

delete old image when upload new image in laravel

delete previous image from folder when updated by new image in laravel

delete old image when upload new one laravel

delete old image from folder in laravel

Need to delete the old image when uploading a new image in Laravel

In any web application, one of the most common use-cases for storing files is storing user uploaded files such as photos and documents. Laravel makes it very easy to store uploaded files using the store method on an uploaded file instance. Call the store method with the path at which you wish to store the uploaded file.

We store the multiple images and files in our local server and live server folder, whenever we want to update any record file or image we check the old file or image is exist or not in our folder, and if the file already exists we delete the old one and upload a new file.

It helps to clear our storage and any kind of unnecessary data in our local or live server.

In this given below example, we will discuss how to delete the old image when uploading a new image in laravel, and how to edit and update the product data and image in the laravel application.

We will remove the old image from the folder and upload the new image to our Laravel application.

Let’s see an example below -:

Generating Migration with Model :

php artisan make:model Product -m

Migration Structures :

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('product_image');
            $table->float('price');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

Run Migration :

php artisan migrate
product table migration

app\Models\Product.php :

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;
}

Create a Controller :

php artisan make:controller ProductController

routes\web.php :

<?php

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

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/


#Delete previous image from folder when updated by new image in Laravel

Route::get('/add-product', [ProductController::class, 'addProduct']);
Route::get('/list-product', [ProductController::class, 'listProduct']);
Route::post('/store-product', [ProductController::class, 'storeProduct'])->name('product.store');
Route::get('/edit-product/{id}', [ProductController::class, 'editProduct'])->name('product.edit');
Route::post('/update-product/{id}', [ProductController::class, 'updateProduct'])->name('product.update');

app\Http\Controllers\PostController.php :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;
use File;

class ProductController extends Controller
{

    public function addProduct(){
        return view('product.create');
    }

    public function listProduct()
    {
        $products = Product::get();
        return view('product.list',compact('products'));
    }

    public function storeProduct(Request $request){

        #Handle Product Img Upload
        if($request->hasFile('product_image'))
        {
            $filenameWithExt = $request->file('product_image')->getClientOriginalName();
            $filename  = pathinfo($filenameWithExt, PATHINFO_FILENAME);
            $extension = $request->file('product_image')->getClientOriginalExtension();
            $fileNameToStore = $filename . '_' . time() . '.' . $extension;
            $request->product_image->move(public_path('/uploads/product'), $fileNameToStore);
        }
        else
        {
            $fileNameToStore = 'No Img Found!';
        }
        $product = new Product();
        $product->product_name  = $request->name;
        $product->product_image = $fileNameToStore;
        $product->price         = $request->price;
        $product->save();
        dd('Product uploaded Successfully');
    }

    public function editProduct($id){
        $product = Product::find($id);
        return view('product.edit',compact('product'));
    }

    public function updateProduct(Request $request, $id)
    {
        $product = Product::find($id);
        #Check if uploaded file already exist in Folder
        if($request->hasFile('product_image'))
        {
            #Get Image Path from Folder
            $path = 'uploads/product/'.$product->product_image;
            if(File::exists($path))
            {
                File::delete($path);
            }

            #If File is new and not Exist in Folder
            $filenameWithExt = $request->file('product_image')->getClientOriginalName();
            $filename  = pathinfo($filenameWithExt, PATHINFO_FILENAME);
            $extension = $request->file('product_image')->getClientOriginalExtension();
            $fileNameToStore = $filename . '_' . time() . '.' . $extension;
            $request->product_image->move(public_path('/uploads/product'), $fileNameToStore);

            $product->product_name  = $request->name;
            $product->product_image = $fileNameToStore;
            $product->price         = $request->price;
            $product->save();
            dd('Product updated Successfully');
         }
    }
}
Import in your controller:

use File;

Create Blade Files :

We create a product folder in views and then create these 3 files given below-:

  • create.blade.php
  • list.blade.php
  • edit.blade.php

resources\views\product\create.blade.php :

create blade file
<!DOCTYPE html>
<html>
   <head>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
   </head>
   <main>
      <br><br>
      <div class="container">
         <div class="row justify-content-center">
            <div class="col-lg-6">
               <div class="main">
                  <h4 style="color: #BE206B;">Delete previous image from folder when updated by new image in Laravel Example</h4>
                  <form role="form" action="{{ route('product.store') }}" method="post" enctype="multipart/form-data">
                     @csrf
                     <div class="form-group">
                        <label for="name">Name<span class="text-danger">*</span></label>
                        <input type="text" name="name" class="form-control" required>
                     </div>
                     <div class="form-group">
                        <label for="price">Price<span class="text-danger">*</span></label>
                        <input type="text" name="price" class="form-control" required>
                     </div>
                     <div class="form-group">
                        <label for="image">Image<span class="text-danger">*</span></label>
                        <input type="file" name="product_image" class="form-control" required>
                     </div>
                     <div class="form-group">
                        <button type="submit" class="btn btn btn-secondary">Save Product</button>
                     </div>
                  </form>
               </div>
            </div>
         </div>
      </div>
   </main>
   </body>
</html>

Related article : Image validation in Laravel 8.

resources\views\product\list.blade.php :

list blade file
<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Product List Data</title>
      <meta charset="utf-8">
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" ></script> 
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css"  />
   </head>
   <body>
      <div class="container">
         <h3 style="color: #BE206B;">Product List Data</h3>
         <table class="table">
            <thead>
               <tr>
                  <th>S.no</th>
                  <th>Product Name</th>
                  <th>Product Price</th>
                  <th>Product image</th>
                  <th>Action</th>
               </tr>
            </thead>
            <tbody>
               @foreach($products as $key => $product)
               <tr>
                  <th scope="row">{{ $key+1 }}</th>
                  <td>{{ $product->product_name }}</td>
                  <td>{{ $product->price}}</td>
                  <td> 
                  <img src="{{ url('/uploads/product/'.$product->product_image) }}" width="120" height="110" /> 
                  </td>
                  <td><a href="{{route('product.edit',$product->id)}}">Edit Product</a></td>
               </tr>
            </tbody>
            @endforeach
         </table>
      </div>
   </body>
</html>

Recommended article : Encrypt and Decrypt Id in Laravel.

resources\views\product\edit.blade.php :

edit blade file laravel
<!DOCTYPE html>
<html>
   <head>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
   </head>
   <main>
      <div class="container">
         <div class="row justify-content-center">
            <div class="col-lg-6">
               <div class="main">
                  <h4 style="color: #BE206B;">Delete previous image from folder when updated by new image in Laravel Example</h4>
                  <br>
                  <form role="form" action="{{ route('product.update',$product->id) }}" method="post" enctype="multipart/form-data">
                     @csrf
                     <div class="form-group">
                        <label for="name">Name<span class="text-danger">*</span></label>
                        <input type="text" name="name" value="{{ $product->product_name }}" class="form-control" required>
                     </div>
                     <div class="form-group">
                        <label for="price">Price<span class="text-danger">*</span></label>
                        <input type="text" name="price" value="{{ $product->price }}" class="form-control" required>
                     </div>
                     <div class="form-group">
                        <label for="image">Image<span class="text-danger">*</span></label>
                        <img src="{{ url('/uploads/product/'.$product->product_image) }}" width="120" height="110" /> 
                        <input type="file" name="product_image" class="form-control">
                     </div>
                     <div class="form-group">
                        <button type="submit" class="btn btn btn-secondary">Update Product</button>
                     </div>
                  </form>
               </div>
            </div>
         </div>
      </div>
   </main>
   </body>
</html>

Run application :

http://127.0.0.1:8000/list-product
edit and delete old image from folder in laravel

delete image store in laravel

new image store in laravel

In this article, we learned “How to delete the old image when uploading a new image in Laravel”, I hope this article will help you with your Laravel application Project.

Read also-: How to create multiple route files in Laravel 8.

Hi, My name is Gaurav Pandey. I'm a Laravel developer, owner of 8Bityard. I live in Uttarakhand - India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Javascript, JQuery, Laravel, WordPress. connect@8bityard.com