首页 > 解决方案 > 自动构建 laravel 分页对象

问题描述

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

$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 魔术方法来自动构建分页有效负载大批?

标签: phplaravel

解决方案


您可以使用 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;

推荐阅读