How to Delete File or image from project Folder & store data in laravel 6.x using controller

How to Delete File or image from project Folder & store data in laravel 6.x using controller

How to Delete File or image from project Folder & store data in laravel 6.x using controller

How to Delete File or image from project Folder & store data in laravel 6.x using controller


Suppose we a products table in our product table we will store data with product_name, Product_price and product_image now we want to delete product details with image from our project folder and also database.

When we will store a product details with image will save image path or url in our product table. and image will save

project> public/uploads/products/

For store we should have a controller : ProductController.php

At first we should write two route for store and delete

For store data

//store route
Route::get('/product/store', [
    'uses' => 'ProductController@store',
    'as' => 'product.store'
]);
For delete data
//delete route
Route::get('/product/{id}', [
    'uses' => 'ProductController@destroy',
    'as' => 'product.delete'
]);
Now in our controller we will use store function for upload or store data in product table by using this code.

Store function:
 
public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'description' => 'required',
            'price' => 'required',
            'image' => 'required|image'
        ]);

        $product = new Product;
        $product_image = $request->image;
        $product_image_new_name = time() . $product_image->getClientOriginalName();
        $product_image->move('uploads/products', $product_image_new_name);
        $product->name = $request->name;
        $product->description = $request->description;
        $product->price = $request->price;
        $product->image = 'uploads/products/' . $product_image_new_name;

        $product->save();
        Session::flash('success', 'Product created.');
        return redirect()->route('products.index');
    }
Destroy or delete function:
 
  public function destroy($id)
    {
        $product = Product::find($id);
        if(file_exists($product->image))
        {
            unlink($product->image);
        }
        $product->delete();
        Session::flash('success', 'Product deleted.');
        return redirect()->back();
    }
At first we will find ID for delete data from product table and use a condition for find the exists file on that id and use unlink($product->image); method for delete file from folder and also path from table.

If you have any query please comment us blew the post. share if you do think...


  • laravel 6.x
  • How to Delete File
  • delete image from folder
  • laravel file delete from folder
  • how to store laravel
  • laravel controller store
  • laravel destroy function
  • store function
  • Comments