Deleting local product image Laravel

5

Well I have a product and I have an image being recorded locally.

I need the backend when the product is deleted the local image is deleted.

When I delete it, it deletes the data from the database, deletes the image information in the database, but does not delete the local image.

What would be the best way to do it?

My route:

Route::get('/{id}/destroy',['as'=>'products.destroy', 'uses'=>'AdminProductsController@destroy']);

My function to delete the product:

public function destroy($id)
{
    $this->productModel->find($id)->delete();

    return redirect()->route('products');
}

Function to remove image in image view

 public function destroyImage(ProductImage $productImage, $id)
{
    $image = $productImage->find($id);

    if(file_exists(public_path() .'/uploads/'.$image->id.'.'.$image->extension)) {

        Storage::disk('public_local')->delete($image->id . '.' . $image->extension);
    }

    $product = $image->product;
    $image->delete();


    return redirect()->route('products.images', ['id'=>$product->id]);

}
    
asked by anonymous 17.06.2015 / 20:57

1 answer

1

When deleting the product, your destroy method must also delete the created file.

You can do this directly in the method:

public function destroy($id)
{
    $disk = Storage::disk('local');

    $this->productModel->find($id);
    $disk->delete($this->productModel->filePath);

    $this->productModel->delete();

    return redirect()->route('products');
}

A more elegant way would be to use the event % of Eloquent% :

In the deleting() method of your boot() enter:

public function boot()
{
    \Namespace\Para\Product::deleting(function ($product) {
         Storage::disk('local')->delete($product->filePath);

         return true;
    });
}

PS: I'm assuming you're storing the file name in the database ( app\Providers\AppProvider.php )

    
17.06.2015 / 21:45