How to Delete File or image from project Folder & store data in laravel 6.x using controller
- Post by: Public
- on: 23-09-19
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 routeNow in our controller we will use store function for upload or store data in product table by using this code.
Route::get('/product/{id}', [
'uses' => 'ProductController@destroy',
'as' => 'product.delete'
]);
Store function:
public function store(Request $request)Destroy or delete function:
{
$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');
}
public function destroy($id)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.
{
$product = Product::find($id);
if(file_exists($product->image))
{
unlink($product->image);
}
$product->delete();
Session::flash('success', 'Product deleted.');
return redirect()->back();
}
If you have any query please comment us blew the post. share if you do think...
Comments