You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel分页查询中添加自定义参数?

Laravel分页保留自定义搜索参数解决方案

问题说明

当前使用Laravel分页时,跳转后仅保留page参数,需让分页链接包含key、role、from、to等自定义搜索参数,目标链接格式为:
http://localhost:8000/customers?key=ang&role=&from=&to=&page=2

现有查询代码:

$users = User::orderBy('id', 'DESC')
                ->where($column, $operator, $num)
                ->where('email', 'LIKE', "%$key%")
                ->whereBetween('created_at', [$from, $to])
                ->paginate(10);

解决方法

Laravel分页器的appends()方法可用于追加自定义参数到分页链接,具体操作如下:

  • 收集需要保留的参数
    从请求中获取所有需要在分页时保留的搜索参数,包含查询依赖的所有条件:

    $params = request()->only(['key', 'role', 'from', 'to', 'column', 'operator', 'num']);
    
  • 追加参数到分页实例
    在paginate()后链式调用appends(),传入收集到的参数:

    $users = User::orderBy('id', 'DESC')
                    ->where($column, $operator, $num)
                    ->where('email', 'LIKE', "%$key%")
                    ->whereBetween('created_at', [$from, $to])
                    ->paginate(10)
                    ->appends($params);
    
  • (可选)保留全部请求参数
    若需保留URL中所有参数,无需手动指定,直接传入request()->all():

    $users = User::orderBy('id', 'DESC')
                    ->where($column, $operator, $num)
                    ->where('email', 'LIKE', "%$key%")
                    ->whereBetween('created_at', [$from, $to])
                    ->paginate(10)
                    ->appends(request()->all());
    
  • 前端输出分页链接
    在Blade模板中正常渲染分页链接即可:

    {{ $users->links() }}
    

此时生成的分页链接将包含所有自定义参数,符合需求格式。

内容的提问来源于stack exchange,提问作者elbaable

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 05:00:33