LadyDeathKZN
1 month ago
424
12
Laravel

Detach and unlink images

Posted 1 month ago by LadyDeathKZN

Hi,

I have a pivot table that is storing the image_path and product_id. I can update and store with no issues. I want to know how to unlink and delete these pivot table entries at the same time, so the records get deleted and the image itself.

Controller

public function destroy($id)
    {
        $product = Product::find($id);
        unlink(public_path($product->main_image));
        $product->attributesProducts()->detach();
        $product->imageProducts()->detach();
        $product->delete();
        return redirect()->route('products.index')->with('error', 'Product deleted successfully');
    }

Product Model

public function imageProducts()
    {
        return $this->belongsToMany(ImageProduct::class, 'image_products', 'product_id', 'image_path');
    }

Please sign in or create an account to participate in this conversation.