我正在尝试获取用户用车,效果很好。但是我想添加if语句,它应该返回错误消息no record found
。我正在尝试如下
$UserCars = User::with('cars')->findOrFail(request()->user()->id);
if ($UserCars !== null) {
$Result = $UserCars->cars;
}else{
$Result = response()->json(['data' => 'Resource not found'], 404);
}
return new CarResource($Result);
问题是当if语句true
(表示在数据库中找到记录时)时它正在工作,但是如果条件错误,它将返回带有以下消息的html页面
Sorry, the page you are looking for could not be found.
CarResource
是我用于API的API资源。
有人可以请我指导一下,我将不胜感激。谢谢
该find()
方法与该方法之间存在很大差异findOrFail()
。
findOrFail()
ModelNotFound
没有可用结果时将触发异常。要更改此类异常的输出(不执行try catch()),您需要在中的render()
方法中拦截该异常App\Exceptions\Handler::class
。告诉我是否要举个例子。
另一个非常简单的方法是简单地进行查找。
$UserCars = User::with('cars')->find(request()->user()->id);
//this will return either an instance of User or null
if ($UserCars) {
$Result = $UserCars->cars;
$response = new CarResource($Result);
}else{
$response = response()->json(['data' => 'Resource not found'], 404);
}
return $response;
同样,由于您正在为request()
帮助程序恢复用户,因此无需再次从DB请求用户,只需这样做。
$user = $request->user();
if ($user) {
$response = new CarResource($user->cars);
} else {
$response = response()->json(['data' => 'Resource not found'], 404);
}
return $response;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句