【问题标题】:How to return custom API response for "No query results for model", Laravel如何为“模型没有查询结果”返回自定义 API 响应,Laravel
【发布时间】:2016-05-29 20:17:34
【问题描述】:

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

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

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

当请求一个不存在的资源时,Laravel 会自动返回 NotFoundHttpException

NotFoundHttpException

我想返回我自己的自定义响应,但是对于使用路由模型绑定完成的查询,我该如何做到这一点?

Dingo API response answer 这样的东西能实现吗?

或者我会坚持使用类似这样的旧代码:

public function show($id)
{
    $user = User::find($id);

    if ( ! $user ) {
        return $this->respondNotFound('User does not exist');
    }

    return $this->respond($this->userTransformer->transform($users));
}

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

【问题讨论】:

    标签: php laravel laravel-5.2


    【解决方案1】:

    看看你能不能抓住ModelNotFound。

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 我应该创建自己的处理程序并覆盖该函数吗?
      • 只需将您的回复放在if 中即可,无需创建自己的处理程序文件
      • 我尝试将“我自己的测试响应”作为回报;它没有被调用。我仍然在浏览器中收到 NotFoundHttpException
      • 如果你返回类似:response()->json(['message' => 'no resource was found'], 404); 它不起作用?
      • 不幸的是,两者都不起作用。我会尝试类似的东西
      【解决方案3】:

      在 Laravel 7 和 8 中,你可以这样做。

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

      请注意,您应该使用 Throwable 来代替类型提示 Exception 类。

      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);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-23
        • 1970-01-01
        • 2017-10-25
        • 2019-09-16
        相关资源
        最近更新 更多