我和Laravel 5.6
合作,我决定创建一个资源控制器来处理我的一个模型。正确知道我试图从数据库中销毁一条记录,如下所示:
public function destroy(Role $role)
{
$role->delete();
return response([
'alert' => [
'type' => 'success',
'title' => 'Role destroyed!'
]
], 200);
}
它就像$role
存在一样长。我的问题是,我想在$role
不存在这样做的情况下自己处理响应:
return response([
'alert' => [
'type' => 'ups!',
'title' => 'There is no role with the provided id!'
]
], 400);
但相反,我得到这样的错误:
"No query results for model [App\\Models\\Role]."
这是我不想要的。
提前致谢!
"No query results for model [App\\Models\\Role]."
是Laravel中ModelNotFound
例外的标准响应消息。
更改此类异常响应的最佳方法是使用异常处理程序的render函数来响应您想要的任何消息。
例如,你可以做到
if ($e instanceof ModelNotFoundException) {
$response['type'] = "ups!;
$response['message'] = "Could not find what you're looking for";
$response['status'] = Response::HTTP_NOT_FOUND
}
return response()->json(['alert' => $response], $response['status']);
另一种方法是确保不会抛出ModelNotFound
异常(因此在查询模型时使用->find()
而不是->findOrFail()
)然后如果没有返回结果则使用abort helper:
abort(400, 'Role not found');
要么
return response(['alert' => [
'type' => 'ups!',
'title' => 'There is no role with the provided id!']
],400);