如何在Laravel 5分页中默认设置每页计数项目

Pau*_*dev 2 laravel-5

在Laravel 5中,如果我使用,Something::paginate()我将每页获得15个项目。我当然可以随时做Something::paginate(20)

但是,如何覆盖默认计数并使用.env中的值?

fre*_*nus 10

这个问题很久以前就被问到了,但是如果有人需要一种方法来做到这一点,你可以在你的模型中使用一个特征。我必须从请求中获取 per_page 以接受“全部”并返回所有记录,最大不能超过。

<?php

namespace App\Traits;

trait Paginatable
{
    protected $perPageMax = 1000;

    /**
     * Get the number of models to return per page.
     *
     * @return int
     */
    public function getPerPage(): int
    {
        $perPage = request('per_page', $this->perPage);

        if ($perPage === 'all') {
            $perPage = $this->count();
        }

        return max(1, min($this->perPageMax, (int) $perPage));       
    }

    /**
     * @param int $perPageMax
     */
    public function setPerPageMax(int $perPageMax): void
    {
        $this->perPageMax = $perPageMax;
    }
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你...


Yos*_*mza 7

您可以通过以下方式覆盖模型中的$ perPage变量:

   protected $perPage = 10;
Run Code Online (Sandbox Code Playgroud)

在模型内部,该模型将覆盖Model.php中定义的$ perPage = 15原始变量

  • 您可以创建一个扩展 Model 的类,将 $perPage 变量放入其中,然后使所有模型扩展新类,但这也不是最好的解决方案。 (2认同)