Red Velasco
Red Velasco

Reputation: 103

Try Catch method in destroy function laravel

Im trying display a message when you have nothing to delete in the database instead of showing a error that says you have a null value

public function destroy($customer_id)
 {

    $customer_response = [];
    $errormsg = "";

    $customer = Customer::find($customer_id);
    $result = $customer->delete();
    try{
    //retrieve page
      if ($result){
          $customer_response['result'] = true;
          $customer_response['message'] = "Customer Successfully Deleted!";

      }else{
          $customer_response['result'] = false;
          $customer_response['message'] = "Customer was not Deleted, Try Again!";
      }
      return json_encode($customer_response, JSON_PRETTY_PRINT);

    }catch(\Exception $exception){
      dd($exception);
        $errormsg = 'No Customer to de!' . $exception->getCode();

    }

    return Response::json(['errormsg'=>$errormsg]);
  }

the try/catch method is not working compared to my previous store function that is working

Upvotes: 1

Views: 5273

Answers (1)

Kevin Stich
Kevin Stich

Reputation: 783

Read up further on findOrFail. You can catch the exception it throws when it fails to find.

try {
    $customer = Customer::findOrFail($customer_id);
} catch(\Exception $exception){
    dd($exception);
    $errormsg = 'No Customer to de!' . $exception->getCode();
    return Response::json(['errormsg'=>$errormsg]);
}

$result = $customer->delete();
if ($result) {
    $customer_response['result'] = true;
    $customer_response['message'] = "Customer Successfully Deleted!";
} else {
    $customer_response['result'] = false;
    $customer_response['message'] = "Customer was not Deleted, Try Again!";
}
return json_encode($customer_response, JSON_PRETTY_PRINT);

Upvotes: 7

Related Questions