Laravel 提供了强大的分页和排序功能,主要基于 Eloquent ORM 和查询构建器。分页是将大量数据分割成多个页面显示的技术,而排序则是按照特定字段对数据进行升序或降序排列。
// 控制器方法
public function index()
{
$users = User::paginate(10); // 每页10条记录
return view('users.index', compact('users'));
}
public function index(Request $request)
{
$sortField = $request->get('sort', 'id'); // 默认按id排序
$sortDirection = $request->get('direction', 'asc'); // 默认升序
$users = User::orderBy($sortField, $sortDirection)
->paginate(10);
return view('users.index', compact('users'));
}
<!-- resources/views/users/index.blade.php -->
<table>
<thead>
<tr>
<th>
<a href="{{ request()->fullUrlWithQuery(['sort' => 'id', 'direction' => request('direction') === 'asc' ? 'desc' : 'asc']) }}">
ID
@if(request('sort') === 'id')
{{ request('direction') === 'asc' ? '↑' : '↓' }}
@endif
</a>
</th>
<th>
<a href="{{ request()->fullUrlWithQuery(['sort' => 'name', 'direction' => request('direction') === 'asc' ? 'desc' : 'asc']) }}">
Name
@if(request('sort') === 'name')
{{ request('direction') === 'asc' ? '↑' : '↓' }}
@endif
</a>
</th>
<!-- 其他表头 -->
</tr>
</thead>
<tbody>
@foreach($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<!-- 其他列 -->
</tr>
@endforeach
</tbody>
</table>
<!-- 分页链接 -->
{{ $users->links() }}
php artisan vendor:publish --tag=laravel-pagination
然后修改 resources/views/vendor/pagination
下的视图文件
// AppServiceProvider.php
public function boot()
{
Paginator::useBootstrap();
}
public function index(Request $request)
{
$validSortFields = ['id', 'name', 'email', 'created_at'];
$sortField = in_array($request->get('sort'), $validSortFields)
? $request->get('sort')
: 'id';
$sortDirection = $request->get('direction') === 'desc' ? 'desc' : 'asc';
$users = User::with('posts') // 预加载关联
->orderBy($sortField, $sortDirection)
->paginate(10)
->appends($request->query());
return view('users.index', compact('users'));
}
解决方案:
在分页链接后使用 appends()
方法保持查询参数:
$users = User::orderBy($sortField, $sortDirection)
->paginate(10)
->appends($request->query());
解决方案:
simplePaginate()
当不需要显示总页数时cursorPaginate()
解决方案:
$users = User::with(['posts' => function($query) {
$query->orderBy('created_at', 'desc');
}])
->orderBy($sortField, $sortDirection)
->paginate(10);
通过以上方法,您可以轻松在 Laravel 中实现功能完善的分页和排序表格。
没有搜到相关的文章