如何返回“模型没有查询结果”的自定义 API 响应,Laravel


How to return custom API response for "No query results for model", Laravel

我正在Laravel 5.2中构建一个RESTful API。

在我的资源控制器中,我想使用隐式模型绑定来显示资源。

例如
public function show(User $users)
{
    return $this->respond($this->userTransformer->transform($users));
}

当对不存在的资源发出请求时,Laravel会自动返回NotFoundHttpException。

NotFoundHttpException

我想返回自己的自定义响应,但如何为使用路由模型绑定完成的查询执行此操作?

像这样的DingoAPI响应答案能够实现吗?

或者我会坚持我的旧代码,它是这样的:

public function show($id)
{
    $user = User::find($id);
    if ( ! $user ) {
        return $this->respondNotFound('User does not exist');
    }
    return $this->respond($this->userTransformer->transform($users));
}

所以我可以查看是否找不到资源(用户)并返回适当的响应。

看看你是否能抓住ModelNotFound

public function render($request, Exception $e)
{
    if ($e instanceof 'Illuminate'Database'Eloquent'ModelNotFoundException) {
        dd('model not found');
    }
    return parent::render($request, $e);
}

我认为一个好地方是在/app/Exceptions下的Handler.php文件中

public function render($request, Exception $e)
{
    if ($e instanceof NotFoundHttpException) {
        // return your custom response
    }
    return parent::render($request, $e);
}

在 Laravel 7 和 8 中,您可以执行类似操作。

在 app/Exception/Handler.php 类中,添加如下所示的 render() 方法(如果它不存在)。

请注意,您应该使用 Throwable 而不是类型提示异常类。

use Throwable;
public function render($request, Throwable $e)
{
    if ($e instanceof 'Illuminate'Database'Eloquent'ModelNotFoundException) {
        //For API (json)
        if (request()->wantsJson()) {
            return response()->json([
                'message' => 'Record Not Found !!!'
            ], 404);
        }
        //Normal 
        return view('PATH TO YOUR ERROR PAGE'); 
    }
    return parent::render($request, $e);
}