【问题标题】:Laravel Json Response Not working as expectedLaravel Json 响应未按预期工作
【发布时间】:2018-11-06 18:48:56
【问题描述】:

响应对象为空时无法获得响应。当对象返回数据时完美运行。

public function show($id)
{
    $associates = Associate::find_by_id($id);
    if(count($associates)<1)
    {
        $output = array('message' => 'No Records Found');
        $status = 204;

    }
    else{
        $output = array('message' => 'success','data'=>$associates);
        $status = 200;
    }
    return response()->json($output,$status);
}

$associate 对象为空时没有响应。 $associate 不为空时的响应:

{
"message": "success",
"data": [
    {
        "first_name": "xxx",
        "last_name": "xxx",
        "mobile": xxxxxxxxxx,
        "email": "xxxxxx@xxxxx",
        "city": "xxxxx",
        "state": "xxxxxx",
        "pincode": "xxxxx"
    }
  ]
}

【问题讨论】:

  • 尝试使用Associate::find($id) 而不是find_by_id
  • @DerekPollard 我为此结果使用多个表的连接,我可以使用 Associate::find($id) 连接吗?

标签: laravel laravel-5.7 jsonresponse


【解决方案1】:

我对状态码 204 有同样的问题。 我相信这是这里造成的。 Illuminate\Foundation\Application 类会捕捉到这个并抛出一个 HttpException。

我相信最简单的解决方法是让控制器返回以下内容:

return Response::make("", 204);

返回空消息。 检查代码中的 status_code 以在前端显示消息。

【讨论】:

    【解决方案2】:

    如果你使用路由模型绑定来查找记录的ID会更容易。欲了解更多信息,请查看https://laravel.com/docs/5.7/routing#route-model-binding

    我认为下面的 sn-p 应该可以工作。

    if ($associates) {
        $output = array('message' => 'success','data'=>$associates);
        $status = 200;
    } else {
        $output = array('message' => 'No Records Found');
        $status = 204;
    }
    

    【讨论】:

      【解决方案3】:

      我重写了函数供你参考。

      顺便说一句。如果函数只返回一条记录,变量名一般用单数名词。

      public function show($id)
      {
          // Use find() instead of find_by_id()
          $associate = Associate::find($id);
      
          // $associate will be null if not matching any record.
          if (is_null($associate)) {
      
              // If $associate is null, return error message right away.
              return response()->json([
                  'message' => 'No Records Found',
              ], 204);
          }
      
          // Or return matches data at the end.
          return response()->json([
              'message' => 'success',
              'data' => $associate,
          ], 204);
      }
      

      【讨论】:

      • 不工作,试过了。是的,我正在使用多个连接,所以我使用我的自定义模型函数。
      • 好的,我现在明白你为什么要使用自定义函数了。但是当不匹配函数中的任何记录时会返回什么值?我的观点是价值可能是关键。
      猜你喜欢
      • 2014-08-26
      • 2018-02-11
      • 2018-06-05
      • 1970-01-01
      • 1970-01-01
      • 2014-03-26
      • 2020-04-26
      • 2017-12-21
      • 2020-10-20
      相关资源
      最近更新 更多