項目中,分頁經常會用到。
Laravel 中也自帶了分頁功能。
但有些時候需要稍作修改,來滿足自己的需求。
一、普通分頁
1、控制器中,用 paginate() 方法。
$users = DB::table('users')->paginate(15);
或簡單分頁
$users = DB::table('users')->simplePaginate(15);
2、blade 模板中,可直接用查詢結果數據
{{ $users->links() }}、{{ $users->render() }}
分頁自帶了 bootstamp 樣式
3、自定義分頁 URI
$users->withPath('custom/url');
4、附加參數到分頁
$users->appends(['sort' => 'votes'])->links()
二、自定義分頁
1、自定義分頁模板
php artisan vendor:publish --tag=laravel-pagination
會在 resources/views 目錄下自動創建 pagination/ 目錄
會把自帶分頁中的模板 copy 在以上目錄中。
2、修改模板
比如修改顯示鏈接數,分頁內容等。
3、調用自定義模板
$paginator->links('view.name')
links 參數為模板路徑
三、集合中的分頁
很多時候查詢結果需要用 Collection 處理后再分頁,而 Laravel 中是不支持的。
下面稍作修改,來實現上面的需求
1、集合處理查詢結果
$users = DB::table('users') ->get() ->each(function($item, $key){ $item->total = 11; })->paginate(15);
經過上面的處理后,會發現分頁消失了。
2、分頁加入服務提供者中
在 app/Providers/AppServiceProvider.php 文件,
頭部引入下面類
use Illuminate\Pagination\Paginator; use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Support\Collection;
boot 方法中添加以下代碼
if (!Collection::hasMacro('paginate')) { Collection::macro('paginate', function ($perPage = 15, $page = null, $options = []) { $page = $page ?: (Paginator::resolveCurrentPage() ?: 1); return (new LengthAwarePaginator( $this->forPage($page, $perPage), $this->count(), $perPage, $page, $options)) ->withPath(''); }); }
再去測試,發現分頁又回來了。