【问题标题】:Laravel 5 response()->json always returns an array?Laravel 5 response()->json 总是返回一个数组?
【发布时间】:2015-08-08 08:55:47
【问题描述】:

有没有办法阻止 laravel 总是返回一个数组,不管是否只有一个元素?我检查了文档并提出不足。如果就是这样当然很好,只是看起来有点傻,因为如果只有一个元素,你就不会将数组发布到端点!

为了理智,返回有效载荷:

[
    {
        "id": 1,
        "created_at": "2015-05-22 15:41:24",
        "updated_at": "2015-05-22 15:41:24",
        "deleted_at": null,
        "closed_loop_interaction_type_id": 1,
        "interaction_note": "Test Interaction note",
        "closed_loop_processes_id": 1,
        "interaction_type": {
            "id": 1,
            "created_at": "2015-05-22 15:41:24",
            "updated_at": "2015-05-22 15:41:24",
            "deleted_at": null,
            "type": 0,
            "method": "Phone Call (mobile)"
        }
    }
]

这是一个对象,但作为 1 的数组返回。有没有办法阻止这种情况?是我填充模型的方式吗?

$query = ClosedLoopInteraction::with('interactionType');
// Construct a list of headers
$headers = \HeaderHelper::generatePaginationHeader($page, $query, 'closedloop', $limit);
\QueryHelper::handleQueryFiltering(
    $query, ['limit'=> $limit, 'page' => $page]);
$response = response()->json($query->get(), \ApiResponse::$STATUS_OK);
// Add the constructed headers to the response
\HeaderHelper::addHeadersToResponse($response, $headers);
return $response;

【问题讨论】:

    标签: php json eloquent laravel-5


    【解决方案1】:

    使用查询first() 方法而不是get() 方法

    【讨论】:

      【解决方案2】:

      好吧,Laravel 从后面使用 json_encode 来返回你看到的 JSON,手头有这个,你可以知道当你传递一个数组时,无论长度如何,甚至是 length === 1,你会得到一个数组的输出,因为这就是json_encode 的工作方式,所以你应该按照@Mark Ba​​ker 说的做,并修改以下行:

      $response = response()->json($query->get(), \ApiResponse::$STATUS_OK);
      

      收件人:

      $response = response()->json($query->first(), \ApiResponse::$STATUS_OK);
      

      【讨论】:

        【解决方案3】:

        这取决于。查看您的代码,您将返回一个模型列表。如果是这种情况,您还应该返回一个数组,无论是空的、单个的还是多个模型。这样,返回类型始终相同且更易于处理。但是,如果您查看特定模型、编辑或其他内容,请使用另一个答案建议的方法first()

        【讨论】:

          猜你喜欢
          • 2014-03-09
          • 2018-05-31
          • 2015-09-15
          • 1970-01-01
          • 2021-11-26
          • 2017-08-31
          • 2016-07-19
          • 2016-09-12
          • 2015-12-10
          相关资源
          最近更新 更多