Laravel 不支持对其默认分页进行限制,但如果限制可以通过以下步骤设置分页:
首先在模型内部创建一个静态方法(假设用户模型)
第一步:在 User 模型的命名空间之后添加这两行
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
第二步: 在用户模型中输入以下方法
public static function customPaginate($items,$perPage)
{
//Get current page form url e.g. &page=6
$currentPage = LengthAwarePaginator::resolveCurrentPage();
//Create a new Laravel collection from the array data
$collection = new Collection($items);
//Define how many items we want to be visible in each page
$perPage = $perPage;
//Slice the collection to get the items to display in current page
$currentPageSearchResults = $collection->slice($currentPage * $perPage, $perPage)->all();
//Create our paginator and pass it to the view
$paginatedSearchResults = new LengthAwarePaginator($currentPageSearchResults, count($collection), $perPage);
return $paginatedSearchResults;
}
第三步:在路由或控制器中输入代码以查看结果(假设在 中routes.php
)
Route::get('/', function(){
$users = DB::table('users')->limit(20)->get();
$paginated_result = App\User::customPaginate($users,3);
//dd($paginated_result);
return view('show')->with('paginated_result',$paginated_result);
});
希望它会起作用。