【问题标题】:how can i add last_page in my resource using laravel如何使用 laravel 在我的资源中添加 last_page
【发布时间】:2021-08-21 07:36:36
【问题描述】:

我正在使用 LaravelVueJs 做一个小项目,我尝试做一个无限滚动分页 strong>),因此每次滚动时我都可以加载更多记录。

为此,我需要从分页中获取 last_page 编号。如何在我的资源中添加 last_page。

这是我的代码。(资源)

public function toArray($request)
    {
        return [
            'username'  => $this->username,
            'age'       => $this->age($this),
            // i want to add last_page => here
        ];
    }

这是我的控制器:

public function index(){
        return DatingResource::collection(User::select('*')->where('id', '!=', Auth::user()->id)->paginate(10));
    }

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    你说你想添加一个包含最后一页的数组元素,但这似乎有点奇怪,因为这意味着你要在每个元素中包含它。 如果您想按照设计的方式使用资源,您应该查看documentation,了解如何进行 automagic 分页。

    小sn-p供参考:

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

    应该返回

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

    正如您在此处看到的,该类添加了使分页工作所需的所有必要数据。

    【讨论】:

    • 我不想显示所有我想要只有 id 和 name 例如 + 我的分页系统的字段,我不想显示例如电子邮件
    • 如果您将User::select(*) 更改为User::select('id', 'name'),这不会得到解决
    • @LOO 我希望,但我的资源中有自己的数据结构,例如 [x => [Y]]
    • 是的,通过使用资源、集合和模型,您可以获得您想要的。您限制了 Resource 上的返回数组,并且 Collection 为您提供了一个附有分页的资源集合。你甚至可以使用没有资源的集合,但我相信这不是你想要实现的目标。
    猜你喜欢
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    • 2022-12-13
    • 2022-10-04
    • 2020-06-30
    相关资源
    最近更新 更多