【问题标题】:How to populate META and LINKS pagination on laravel?如何在 laravel 上填充 META 和 LINKS 分页?
【发布时间】:2019-06-30 22:38:01
【问题描述】:

我需要帮助在 laravel eloquent 上填充这种分页。

{
  "meta": {
    "count": 10,
    "total": 100
  },
  "links": {
    "first": "http://localhost/page[limit]=10&page[offset]=0",
    "last": "http://localhost/page[limit]=10&page[offset]=10",
    "next": "http://localhost/page[limit]=10&page[offset]=10",
    "prev": "null"
  },
  "data": [
    {
      "type": "checklists",
      "id": "1"
    }
  ]
}

我在 Laravel Eloquent 上试过这段代码。

$data = Model::select('type','id')->paginate(10);
return response()->json(
    [
        'data' => $data
    ],200
);

但它显示不同的格式,填充的数据没有 META 和 LINKS 架构。

{
    "data": {
        "current_page": 1,
        "data": [
            {
                "type": "Mechanical Equipment Sales Representative",
                "id": 1
            }
       ],
        "first_page_url": "http://localhost?page=1",
        "from": 1,
        "last_page": 4,
        "last_page_url": "http://localhost?page=4",
        "next_page_url": "http://localhost?page=2",
        "path": "http://localhost",
        "per_page": 10,
        "prev_page_url": null,
        "to": 10,
        "total": 39
    }
}

如何做到这一点?请帮忙?

【问题讨论】:

  • 更具体,显示您尝试过的代码
  • 我已经更新了代码。

标签: php laravel eloquent pagination


【解决方案1】:

您可以使用API​​资源:https://laravel.com/docs/eloquent-resources#pagination

创建集合资源:

php artisan make:resource ModelCollection

在你的控制器中使用它:

$data = Model::select('type','id')->paginate(10);

return new ModelCollection($data);

对于 Lumen,创建一个 app/Http/Resources/ModelCollection.php 文件:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class ModelCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return parent::toArray($request);
    }
}

【讨论】:

  • 感谢您的重播。在流明上做这个怎么样?上面没有 make:resource 。是否有任何手动步骤来创建 make:resource?
  • 非常感谢。我手动完成了这种格式,直到我陷入困境,分页如何与资源本身分离。现在我明白了这样做是多么容易。谢谢你,你节省了我的时间。
  • 我有相同型号的不同案例。你想检查一下吗? stackoverflow.com/questions/56864032/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-20
  • 1970-01-01
  • 2021-11-17
  • 2018-02-19
  • 2021-12-21
  • 2014-10-03
相关资源
最近更新 更多