use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
// ...
// 创建一个示例集合
$collection = collect([
['name' => 'John', 'age' => 30],
['name' => 'Jane', 'age' => 25],
['name' => 'Dave', 'age' => 40],
// ...
]);
// 排序和分页操作
$sortBy = 'age'; // 排序字段
$sortOrder = 'asc'; // 排序顺序,可以是 'asc' 或 'desc'
$perPage = 10; // 每页显示的数量
$page = Paginator::resolveCurrentPage('page'); // 获取当前页码,默认为 'page'
// 排序
$sortedCollection = $collection->sortBy($sortBy, SORT_REGULAR, $sortOrder === 'desc');
// 分页
$slicedData = $sortedCollection->slice(($page - 1) * $perPage, $perPage);
$paginatedCollection = new LengthAwarePaginator(
$slicedData,
$sortedCollection->count(),
$perPage,
$page,
['path' => Paginator::resolveCurrentPath()]
);
// 返回包含排序和分页后的集合数据的视图
return view('your-view', ['data' => $paginatedCollection]);
标签:laravel,Paginator,perPage,分页,age,collect,排序,page
From: https://www.cnblogs.com/sanlilin/p/17628109.html