在Laravel 5中,如果我使用Something::paginate()
,我将每页获得15个项目。课程我可以随时做Something::paginate(20)
.
但是如何覆盖默认计数并使用我的 .env 中的值?
$perPage您可以通过将
protected $perPage = 10;
在模型中覆盖模型中定义的 $perPage=15 原始变量.php
这个问题很久以前就被问过了,但如果有人需要一种方法来做到这一点,你可以在模型中使用特征。我必须从请求中获取per_page,以接受"全部"并返回所有记录,最大值不能超过。
<?php
namespace AppTraits;
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;
}
}
希望对你有帮助...