【问题标题】:Laravel 5.5 - API ID not found 404 instead of JSONLaravel 5.5 - API ID 未找到 404 而不是 JSON
【发布时间】:2018-07-21 21:08:08
【问题描述】:

我在这样的 Laravel 5.5 API 路由上使用 findOrFail...

public function getCategory(Request $request, $id) {

    /* Get Category From ID */
    try {
        $category = Category::with('users')->findOrFail($id);
    }

    /* catch(Exception $e) catch any exception */
    catch(ModelNotFoundException $e) {

        /* Return Success Response */
        return Response::json(array(
            'error' => true,
            'status_code' => 400,
            'response' => 'category_id_not_found',
        ));

    }
}

如果我输入的 ID 不存在,则会收到 404 错误而不是 JSON 响应。

我哪里错了?

更新

原来我没有包括

use Illuminate\Database\Eloquent\ModelNotFoundException;

在控制器中,感谢 Sohel0415 让我朝那个方向看。

【问题讨论】:

    标签: laravel


    【解决方案1】:

    试试NotFoundHttpException:

    public function getCategory(Request $request, $id) {
    
    /* Get Category From ID */
     try {
         $category = Category::with('users')->findOrFail($id);
     }
    
     /* catch(Exception $e) catch any exception */
     catch(NotFoundHttpException $e) {
    
         /* Return Success Response */
         return Response::json(array(
            'error' => true,
            'status_code' => 400,
            'response' => 'category_id_not_found',
        ));
    
     }
    }
    

    或者您可以执行以下操作:

    public function getCategory(Request $request, $id) {
    
        $category = Category::with('users')->find($id);
        if($category!=null){
            return Response::json(array(
            'status_code' => 200,
            'category' => $category,
           )); 
        }
    
        return Response::json(array(
            'error' => true,
            'status_code' => 400,
            'response' => 'category_id_not_found',
        ));
    
     }
    }
    

    【讨论】:

      【解决方案2】:

      findOrFail 方法返回一个对象,如果找不到则抛出错误,如Laravel docs,您可能希望使用find 方法并使用if($category) 检查模型是否存在。

      【讨论】:

        猜你喜欢
        • 2019-01-20
        • 2020-10-26
        • 1970-01-01
        • 2021-12-01
        • 2019-02-07
        • 2021-03-21
        • 2019-10-20
        • 2021-02-27
        • 1970-01-01
        相关资源
        最近更新 更多