Laravel 9中Bootstrap分页与列表排序的结合实现方法
实现Laravel 9带排序的分页列表
要同时实现排序和分页,核心是从请求中获取排序参数,安全构建查询并将排序参数附加到分页链接,同时在视图中提供可交互的排序表头。
1. 修改StudentController的index方法
处理请求中的排序字段和方向,限制允许排序的字段避免风险,结合排序与分页:
use Illuminate\Http\Request; use App\Models\Student; public function index(Request $request) { // 定义允许排序的字段,防止传入无效或恶意字段 $allowedSorts = ['name', 'age', 'created_at']; // 获取排序字段,默认使用created_at $sort = in_array($request->input('sort'), $allowedSorts) ? $request->input('sort') : 'created_at'; // 获取排序方向,仅允许asc/desc,默认desc $direction = $request->input('direction') === 'asc' ? 'asc' : 'desc'; // 构建查询:先排序,再分页,同时附加排序参数到分页链接 $students = Student::orderBy($sort, $direction) ->paginate(5) ->appends([ 'sort' => $sort, 'direction' => $direction ]); return view('students.index', compact('students', 'sort', 'direction')); }
2. 视图中添加可交互的排序表头
在students/index.blade.php里,给表头添加可点击链接,点击时切换排序方向,同时显示当前排序状态:
<table class="table table-striped"> <thead> <tr> <!-- 姓名字段排序链接 --> <th> <a href="{{ route('students.index', [ 'sort' => 'name', 'direction' => $sort === 'name' && $direction === 'asc' ? 'desc' : 'asc' ]) }}"> 姓名 @if($sort === 'name') <span class="ms-1">{{ $direction === 'asc' ? '↑' : '↓' }}</span> @endif </a> </th> <!-- 年龄字段排序链接 --> <th> <a href="{{ route('students.index', [ 'sort' => 'age', 'direction' => $sort === 'age' && $direction === 'asc' ? 'desc' : 'asc' ]) }}"> 年龄 @if($sort === 'age') <span class="ms-1">{{ $direction === 'asc' ? '↑' : '↓' }}</span> @endif </a> </th> <!-- 创建时间字段排序链接 --> <th> <a href="{{ route('students.index', [ 'sort' => 'created_at', 'direction' => $sort === 'created_at' && $direction === 'asc' ? 'desc' : 'asc' ]) }}"> 创建时间 @if($sort === 'created_at') <span class="ms-1">{{ $direction === 'asc' ? '↑' : '↓' }}</span> @endif </a> </th> <th>操作</th> </tr> </thead> <tbody> @foreach($students as $student) <tr> <td>{{ $student->name }}</td> <td>{{ $student->age }}</td> <td>{{ $student->created_at->format('Y-m-d H:i') }}</td> <td> <!-- 这里添加编辑、删除等操作按钮 --> </td> </tr> @endforeach </tbody> </table> <!-- Laravel自带分页链接,自动携带排序参数 --> {{ $students->links() }}
关键说明
- 安全校验:通过
$allowedSorts限制可排序字段,避免传入无效字段导致SQL错误或注入风险 - 保持排序状态:使用
appends()方法将sort和direction参数附加到分页链接中,确保分页时不会丢失当前排序规则 - 交互体验:点击表头链接时自动切换排序方向,同时用箭头标识当前排序状态,提升用户体验
内容的提问来源于stack exchange,提问作者Peter de Pradines
相关产品推荐
相关产品推荐

