所以我试图在 Laravel 5 中使用像 localhost/ads/1
这样漂亮的 url 来获得分页,其中 1
代表页面.
据我了解,这样的操作需要重载 AbstractPaginator
或 LengthAwarePaginator
,以修改 Database\Query\Builder
.
我是否遗漏了什么,绑定(bind)或依赖注入(inject),或者是否应该有可能更改我们想要使用的分页器?
最佳答案
最后,我不得不自己编写一个分页器。我在这里发布我的解决方案,它应该对任何人有帮助。
请注意,该解决方案虽然具有功能性,但在实际使用中需要注意(关于验证);此处简化了该类以突出该机制。
<?php namespace App\Services;
use Illuminate\Support\Collection;
use Illuminate\Pagination\BootstrapThreePresenter;
use Illuminate\Pagination\LengthAwarePaginator as BasePaginator;
class Paginator extends BasePaginator{
/**
* Create a new paginator instance.
*
* @param mixed $items
* @param int $perPage
* @param string $path Base path
* @param int $page
* @return void
*/
public function __construct($items, $perPage, $path, $page){
// Set the "real" items that will appear here
$trueItems = [];
// That is, add the correct items
for ( $i = $perPage*($page-1) ; $i < min(count($items),$perPage*$page) ; $i++ ){
$trueItems[] = $items[$i];
}
// Set path as provided
$this->path = $path;
// Call parent
parent::__construct($trueItems,count($items),$perPage);
// Override "guessing" of page
$this->currentPage = $page;
}
/**
* Get a URL for a given page number.
*
* @param int $page
* @return string
*/
public function url($page){
if ($page <= 0) $page = 1;
return $this->path.$page;
}
}
要使用该类,可以定义一个路由
Route::get('items/{page}','MyController@getElements');
然后在上述 Controller 中,在 getElements
中:
$items = new Paginator(Model::all(),$numberElementsPerPage,url('items'),$page);
然后,您可以像往常一样处理您的元素。 注意:我添加了一个路径选项,以便集成更复杂的漂亮 url 设计。 希望对您有所帮助!
关于php - Laravel 5 - 漂亮的分页器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27687481/