【问题标题】:Laravel Eloquent Resource Collection responseLaravel Eloquent 资源收集响应
【发布时间】:2018-03-26 14:54:56
【问题描述】:

所以我尝试使用资源集合来返回数据表 json 信息。在我使用我的收藏之前,我首先做了一个如下所示的概念证明:

public function index()
{
    $clients = QueryBuilder::for(Client::class)
        ->allowedIncludes('accounts')
        ->get();

    if (request()->ajax()) {
        return DataTables::of($clients)->make(true);
    }

    return view('client.index', compact('clients'));
}

这很完美,json 响应看起来像这样:

{data: [{id: "4428", number: "492501", name: "Test Client", email: "test@test.com",…},…]
draw:1
input:{view: "datatable", draw: "1",…}
recordsFiltered:2
recordsTotal:2}

然后我更新了索引调用以使用如下所示的资源集合:

public function toArray($request)
{
    switch ($request->view) {
        case 'datatable':
            self::withoutWrapping();
            return DataTables::of($this->collection)->make(true);
    }
    return parent::toArray($request);
}

响应现在被放入“原始”属性中,并且一堆其他项目被添加到响应中。我不明白为什么。它看起来像这样:

*callback: null
*charset: null
*content: <The above response is in here as a string>
*encodingOptions: 0
*statusCode: 200
*statusText: "OK"
*version: "1.0"
exception: null
headers: {}
original: <The above response is in here as an object>

我可以将 datatables 上的 dataSrc 设置为 original.data,它工作正常,但是所有这些额外的东西是从哪里来的?我已经使用了一些其他资源集合,但从未添加过所有这些东西。

更新:因为我正在寻找的所有内容都在“原始”中,所以分页中断以及大多数其他数据表功能。如果我将此返回移回控制器,它工作正常。

【问题讨论】:

  • 看起来它绕过了 switch 语句并将 $request 作为数组返回。 $request-&gt;view 是什么?它不能匹配“数据表”

标签: laravel eloquent laravel-eloquent


【解决方案1】:

因此,答案与响应类型有关。雄辩的资源有一个名为“toResponse”的未记录函数,如果您的返回将是某种 jsonResponse,您需要修改它而不是您的 toArray 方法。发生的事情是我正在返回一个 JsonResponse 并将其转换为一个数组并仅返回该 json 编码。

为了清楚起见,这是我的新资源:

public function toResponse($request)
{
    switch ($request->view) {
        case 'datatable':
            self::withoutWrapping();
            return DataTables::of($this->collection)->toJson();
    }
    return parent::toResponse($request);
}

因此,重申一下,如果您要返回一个数组或正确地符合数组的东西(数据表 jsonresponse 没有),您将覆盖“toArray”。如果要返回 jsonResponse,则需要覆盖“toResponse”。

另一种选择是让您的代码以toArray 开头,但是当您知道要返回一个jsonResponse 时,您可以调用$this-&gt;toResponse($request)。选项是你的。

【讨论】:

    猜你喜欢
    • 2020-07-04
    • 1970-01-01
    • 2020-06-25
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 2020-01-29
    • 2019-04-11
    • 1970-01-01
    相关资源
    最近更新 更多