API 路由的自定义 findOrFail

Hul*_*ula 4 php laravel laravel-5

我认为这应该默认实施,因为我在routes/api.php.

我想给出 404 错误 JSON 响应,以防我们idfindOrFail()方法上找不到给定参数的任何行。

就像是:

return response()->json([
    'status' => 'ERROR',
    'error' => '404 not found'
], 404);
Run Code Online (Sandbox Code Playgroud)

而不是默认的Sorry, the page you are looking for could not be found.刀片页面。

我不想做:

$item = Model::find($id);
if (is_null($item)) {
    return response()->json([
        'status' => 'ERROR',
        'error' => '404 not found'
    ], 404);
}
Run Code Online (Sandbox Code Playgroud)

在任何地方,当我得到一个id, 我不想在中间件中实现它,因为它会导致 api.php 文件出现一些“混乱”。

pse*_*ime 9

您始终可以在 App\Exceptions\Handler.php 中捕获异常

使用以下命令将异常导入到类中:

use \Illuminate\Database\Eloquent\ModelNotFoundException;
Run Code Online (Sandbox Code Playgroud)

并在渲染方法中,添加

if ($e instanceof ModelNotFoundException) {

            return response()->json([
                'message' => 'Record not found',
            ], 404);

        }
Run Code Online (Sandbox Code Playgroud)


Ric*_* Fu 6

或者使用这个,对我来说看起来更干净:

try {
    $resource = Model::findorfail($id);
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
    return response([
        'status' => 'ERROR',
        'error' => '404 not found'
    ], 404);
}
Run Code Online (Sandbox Code Playgroud)