猿问

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

我需要帮助在 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

    }

}

怎么做?请帮忙?


侃侃尔雅
浏览 124回答 1
1回答

慕容708150

您可以使用 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文件:<?phpnamespace App\Http\Resources;use Illuminate\Http\Resources\Json\ResourceCollection;class ModelCollection extends ResourceCollection{&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Transform the resource collection into an array.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @param&nbsp; \Illuminate\Http\Request&nbsp; $request&nbsp; &nbsp; &nbsp;* @return array&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public function toArray($request)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return parent::toArray($request);&nbsp; &nbsp; }}
随时随地看视频慕课网APP
我要回答