Search code examples
laravelapicontrollerlaravel-8laravel-api

Laravel API - Trying to forbid admins to delete a product if the product is ordered


Like the title says, I'm trying to determine if the product is not ordered, otherwise the admin is able to remove the product. It seems to work, but I think I am not handling it the right way because the console returns an error 500.

This is my destroy function in the ProductController:

public function destroy(Product $product)
{
    $ordersLink = $product->orders()->where('orders.product_id', $product->id)->exists();

    if(!$ordersLink) {
        $status = $product->delete();
    } 

    return response()->json([
        'status' => $status,
        'message' => $status ? 'Product removed' : 'Product not removed'
    ]); 
}

It is throwing an error when the product can't be deleted, but it should return 'Product not removed.'

Any help would be appreciated! Cheers


Solution

  • Replace code with following:

    public function destroy(Product $product)
    {
        $status = false;
        $ordersLink = $product->orders()->exists();
    
        if(!$ordersLink) {
            $status = $product->delete();
        } 
    
        return response()->json([
            'status' => $status,
            'message' => $status ? 'Product removed' : 'Product not removed'
        ]); 
    }