Deleting local image of Laravel product

Asked

Viewed 937 times

5

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

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

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

What’s 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]);

}
  • The local image would be on the machine in the customer?

  • On the local server

1 answer

1

When deleting the product, your method destroy also need to 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 deleting() of Eloquent:

In the method boot() of your app\Providers\AppProvider.php insert:

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 ($product->filePath)

  • Errorexception in Local.php line 200: unlink(C: xampp htdocs public uploads project): Permission denied , I looked for but I was able to resolve this permission error... any tips?

  • You have already set permissions in the folder?

  • I gave permission for everything to 'all''

  • How does a dd($product->filePath) ? The complete path to the file appears?

  • returned null.. I edited the post and posted my image file... thus deleting only the deleted image in the folder..

  • @Raphael am assuming that you are storing the file name in the database ($product->filePath). You need to change this line to the field in your database that stores the file name

  • @Raphael has succeeded ?

  • I had given some time in this project because I’m focused on another.. but then I’ll come back and tell you if I’ve solved it. vlw for help

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.