方式一
使用 Builder 类提供的方法
<?php /** * Set the limit and offset for a given page. * * @param int $page * @param int $perPage * @return $this */ public function forPage($page, $perPage = 15) { return $this->offset(($page - 1) * $perPage)->limit($perPage); }
方式二
定义 扩展 Query Builder
app/Providers/BuilderServiceProvider.php
<?php namespace App\Providers; use Illuminate\Database\Query\Builder; use Illuminate\Support\ServiceProvider; class BuilderServiceProvider extends ServiceProvider { /** * Register services. * * @return void */ public function register() { // } /** * Bootstrap services. * * @return void */ public function boot() { // 分页 Builder::macro('page', function ($page = 1, $size = 10) { return $this->offset(($page - 1) * $size)->limit($size); }); } }
配置 config/app.php
<?php return [ // 省略其他配置 'providers' => [ App\Providers\BuilderServiceProvider::class, ], ];