首页 > 解决方案 > 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

标签: phplaravellaravel-5

解决方案


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;

推荐阅读