donglin7979 2019-04-15 08:44
浏览 89

如何在资源集合中获取分页链接 - Laravel 5.7.19

I am working with laravel API resource. when we don't use any resource collection we get pagination links etc with paginate(10). but when i use Resource::collection i get nothing, just the fields i put in resource.

This is my Controller

return response()->json([
  "items" => LatestProjectsResource::collection(Project::has('pages')->where('type', $type)->latest()->paginate(20))
]);

And this is my Resource

public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->name,
            'slug' => $this->slug,
            'url' => $this->url,
            'thumbnail' => new ThumbnailResource($this->thumbnail),
        ];
    }

Result

enter image description here

I tried some answers from online community including this Customising Laravel 5.5 Api Resource Collection pagination one but its not working

I tried $this->collection but no luck

Please help me out here.

  • 写回答

1条回答 默认 最新

  • dousi6303 2019-04-15 09:02
    关注

    You can get it like

    use App\User;
    use App\Http\Resources\UserCollection;
    
    Route::get('/users', function () {
        return new UserCollection(User::paginate());
    });
    

    see documentation

    The result will be like

    {
        "data": [
            {
                "id": 1,
                "name": "Eladio Schroeder Sr.",
                "email": "therese28@example.com",
            },
            {
                "id": 2,
                "name": "Liliana Mayert",
                "email": "evandervort@example.com",
            }
        ],
        "links":{
            "first": "http://example.com/pagination?page=1",
            "last": "http://example.com/pagination?page=1",
            "prev": null,
            "next": null
        },
        "meta":{
            "current_page": 1,
            "from": 1,
            "last_page": 1,
            "path": "http://example.com/pagination",
            "per_page": 15,
            "to": 10,
            "total": 10
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 蓝桥oj3931,请问我错在哪里
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染