php - How can I make a way to return error message of record not available?
问题描述
I am trying to fetch user cars, which is working fine. But I want to add if-statement which should return a error message no record found
. I am trying as like below
$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);
The problem is it is working when if-statement true
(means when found record in database) but in case of false condition it returns html page with following message
Sorry, the page you are looking for could not be found.
CarResource
is API resource which I am using for API's.
Can someone kindly guide me about this I would appreciate. Thank you
解决方案
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;
推荐阅读
- sony-camera-api - 内容 URL - 索尼相机 API
- python - 仅在 Pandas 中将不规则日期格式转换为年份
- java - 无法自动装配 WebTestClient
- javascript - 正则表达式 C# 与 javascript 不一致
- javascript - JS / Canvas - 如何仅在按下键时更新 draw() 函数?
- html - 当我减小浏览器窗口大小时,使 2 张图像留在我背景上的固定位置
- android - 改版本为Androidx后,没有变成mqtt connect
- c++ - 我想知道缩放和轨道哪里出了问题
- javascript - 具有历史实现和主题标签功能的 ajax 页面加载内容
- reactjs - React ref.current.getBoundingClientRect().width on Change 总是落后一步