Laravel 5 - 漂亮的分页师

rep*_*lia 5 php pagination laravel laravel-5

因此,我试图在Laravel 5中获得分页,localhost/ads/1其中包括1代表页面的漂亮网址.

根据我的理解,这样的操作将需要超载AbstractPaginator,或者LengthAwarePaginator,旨在修改Database\Query\Builder.

我是否遗漏了某些内容,绑定或依赖注入,或者是否有可能更改我们想要使用的分页器?

rep*_*lia 3

最后,我不得不给自己编写一个分页器。我在这里发布我的解决方案,它应该对任何人有帮助。

请注意,该解决方案虽然功能强大,但需要注意实际使用(关于验证);此处简化了该类以突出该机制。

<?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;
    }
}
Run Code Online (Sandbox Code Playgroud)

要使用该类,您可以定义一个路由

Route::get('items/{page}','MyController@getElements');
Run Code Online (Sandbox Code Playgroud)

然后在所述控制器中getElements

$items = new Paginator(Model::all(),$numberElementsPerPage,url('items'),$page);
Run Code Online (Sandbox Code Playgroud)

然后,您可以像平常一样处理您的元素。注意:我添加了一个路径选项,以便集成更复杂的漂亮网址设计。希望能帮助到你!