Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bekaskaki's avatar

Delete Data product

I have 3 tables

  • product
id,name,price
  • sale
id, product_id,sale_price
  • purchase
id, product_id,purchase_price

how to delete a product, if the data sale and purchase 0 then the product will be deleted but if the data is not 0 the product will not deleted

I use this:

 public function destroy($id)
    {
        $products = Product::find($id);
        if (count($products->sale_detail) == 0 && count($products->purchase_detail) == 0) {
            $products->delete;
            return redirect($this->title)->with('success', 'Procuct Deleted!!');
        } else {
            return redirect($this->title)->with('error', 'Something Went Wrong!!');
        }
    }

but it doesn't work

model product:

  public function purchase_detail()
    {
        return $this->hasMany('App\Model\PurchaseDetail');
    }

 public function sale_detail()
    {
        return $this->hasMany('App\Model\SaleDetail');
    }

model sale:

 public function product()
    {
        return $this->belongsTo(App\Model\Product);
    }

model purchase:

 public function product()
    {
        return $this->belongsTo(App\Model\Product);
    }
0 likes
2 replies
mstrauss's avatar
mstrauss
Best Answer
Level 14

Hi @bekaskaki

Try this:

foreach (Product::doesnthave('sale')->doesnthave('purchase')->get() as $product) {
    $product->delete(); 
}
janosk's avatar

Beside that you might missing "()" after delete

$products->delete();

What error do you encounter? (Just hint, products -plural- might be misleading, since you try to fint one product by id)

Please or to participate in this conversation.