【问题标题】:Automatically build laravel pagination object自动构建 laravel 分页对象
【发布时间】:2020-05-14 22:59:07
【问题描述】:

在我的应用程序中,每次我从数据库中检索分页结果时,我都必须这样做:

$posts = Post::latest()->with(['category','user'])->paginate($request->input('paginate', 6));

        $posts = 
        [
            'data' => $posts,
            'pagination' => [
                'total' => $posts->total(),
                'per_page' =>$posts->perPage(),
                'current_page' => $posts->currentPage(),
                'last_page' => $posts->lastPage(),
                'from' => $posts->firstItem(),
                'to' => $posts->lastItem()
            ] 
        ];

如你所见,我首先从数据库中检索结果,然后我必须手动创建分页数据数组,老实说,总是做同样的事情对我来说似乎很糟糕和乏味,我想知道是否有一个 laravel 魔术方法来自动构建分页负载数组?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您可以使用 Eloquent:API 资源“https://laravel.com/docs/7.x/eloquent-resources

    你应该创建一个资源:php artisan make:resource PostCollection

    你应该改变方法toArray($request)这样的东西:

    public function toArray($request)
    {
        return [
            'data' => $this->collection,
            'pagination' => [
                'total' => $this->total(),
                'per_page' =>$this->perPage(),
                'current_page' => $this->currentPage(),
                'last_page' => $this->lastPage(),
                'from' => $this->firstItem(),
                'to' => $this->lastItem()
            ]
        ];
    }
    

    现在,当您想为模型分页时,您只需这样做:

    //Get posts
    $posts = Post::latest()->with(['category','user'])
        ->paginate($request->input('paginate', 6)));
    
    //Use your resource (Collection)
    $postsPaginate = new PostCollection($posts);
    
    //Return your resource
    return $porstsPaginate;
    

    【讨论】:

      猜你喜欢
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 2017-07-30
      • 2019-05-24
      • 2015-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多