在destroy function laravel

时间:2016-12-13 05:16:35

标签: php laravel try-catch

我在数据库中没有要删除的内容时尝试显示消息,而不是显示一个表示您具有空值的错误

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]);
  }

与我之前正在使用的商店功能

相比,try / catch方法无法正常工作

1 个答案:

答案 0 :(得分:3)

findOrFail上进一步阅读。您可以捕获它找不到时抛出的异常。

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);