为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
长风秋雁 2021-04-08 14:15:47
我正在使用laravel API资源。当我们不使用任何资源集合时,我们会获得带有paginate(10)的分页链接等。但是当我使用Resource :: collection时,我什么也没得到,只有我放入资源中的字段。这是我的控制器return response()->json([  "items" => LatestProjectsResource::collection(Project::has('pages')->where('type', $type)->latest()->paginate(20))]);这是我的资源public function toArray($request)    {        return [            'id' => $this->id,            'title' => $this->name,            'slug' => $this->slug,            'url' => $this->url,            'thumbnail' => new ThumbnailResource($this->thumbnail),        ];    }结果我尝试了来自在线社区的一些答案,包括此定制Laravel 5.5 Api资源集合分页之一,但无法正常工作我尝试过$this->collection但没有运气请在这里帮助我。
查看完整描述

2 回答

?
30秒到达战场

TA贡献1828条经验 获得超6个赞

我已经通过重写常规资源类的collection 方法解决了此问题。


public static function collection($data)

{

    /* is_a() makes sure that you don't just match AbstractPaginator

     * instances but also match anything that extends that class.

     */

    if (is_a($data, \Illuminate\Pagination\AbstractPaginator::class)) {

        $data->setCollection(

            $data->getCollection()->map(function ($listing) {

                return new static($listing);

            })

        );


        return $data;

    }


    return parent::collection($data);

}

这只是检查给定的数据是否是Laravel分页器类的实例,如果是,它只是修改基础集合并返回相同的分页器实例。您可以将其放在抽象集合类或每个资源类中。


查看完整回答
反对 回复 2021-04-23
?
跃然一笑

TA贡献1826条经验 获得超6个赞

为了使您的代码整洁,请在不同的集合中使用PaginationResource,并在单个位置上编辑分页详细信息


然后在任何资源中添加您的分页资源,如下所示


这是分页资源

public function toArray($request) : Array

    {

        return [

            'total' => $this->total(),

            'count' => $this->count(),

            'per_page' => $this->perPage(),

            'current_page' => $this->currentPage(),

            'total_pages' => $this->lastPage()

        ];

    }

并将其添加到其他任何这样的集合中


 public function toArray($request) : Array

    {

        $pagination = new PaginationResource($this);


        return [

            'templates' => $this->collection,

            $pagination::$wrap => $pagination,

        ];

    }


查看完整回答
反对 回复 2021-04-23
  • 2 回答
  • 0 关注
  • 194 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信