如何在laravel上填充META和LINKS分页?

时间:2019-06-30 12:58:00

标签: php laravel eloquent pagination

我需要帮助来对雄辩的雄性进行这种分页。

{
  "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
    }
}

该怎么做?请帮忙吗?

1 个答案:

答案 0 :(得分: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);

对于流明,创建一个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);
    }
}