分页:条件分页第一页正常,第二页异常,求大神指点,已附简洁代码。

1. 运行环境

1)Laravel 5.3

2)php7.4

3)CentOS 7.2

2. 分页:条件分页第一页正常,第二页异常,求大神指点

    public function index(Request $request)
    {
        $start = $request->start;
        $end = $request->end;
        $type = $request->type;
        if ($start != null && $end != null){
            $logs = Log::where('type',$type)
            ->whereDate('created_at','>=',$start)
            ->whereDate('created_at','<=',$end)
            ->orderBy('created_at','desc')
            ->paginate(16);
            return view('log.index',compact('logs'));
        }
        $logs = Log::paginate(16);
        return view('log.index',compact('logs'));
    }

视图

{{-- 查询表单 --}}
<form method="GET" action="{{ route('log.index') }}" >
  <span>开始日期:</span>
  <input type="date" name="start"   value="" required />
  <br>
  <span>结束日期:</span>
  <input type="date" name="end"   value="" required  />
  <span>日志类型:</span>
  <input type="text" name="type"   value="" required>
  <button type="submit" >查询</button>
</form>
{{-- 日志 --}}
@foreach($logs as $log)
.
.
.
@endforeach

{{-- 分页 --}}
<div class="page">
  {{$logs->links()}} <span>共有数据:{{$logs->total()}}</span>
</div>

3. 结果

无查询时一切正常;
有查询时,第一页正常,第二页异常。

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
最佳答案

翻页后异常,是因为翻页后搜索条件的丢失,你需要在 自定义分页的 URL

1年前 评论
讨论数量: 7

什么异常?

1年前 评论
王大牛 (作者) 1年前
yilong (楼主) 1年前
yilong (楼主) 1年前

可能你laravel版本太低,试试这个

每页有多个 Paginator 实例
有时您可能需要在应用程序呈现的单个屏幕上呈现两个单独的分页器。 但是,如果两个分页器实例都使用 page 查询字符串参数来存储当前页面,则两个分页器会发生冲突。 要解决此冲突,您可以通过提供给 paginate、simplePaginate 和 cursorPaginate 方法的第三个参数传递您希望用于存储分页器当前页面的查询字符串参数的名称:

use App\Models\User;

$users = User::where('votes', '>', 100)->paginate(
    $perPage = 15, $columns = ['*'], $pageName = 'users'
);
1年前 评论

翻页后异常,是因为翻页后搜索条件的丢失,你需要在 自定义分页的 URL

1年前 评论

问题解决了,翻页后异常,是因为翻页后搜索条件丢失,加上条件就好了,修正如下:

    public function index(Request $request)
    {
        $start = $request->start;
        $end = $request->end;
        $type = $request->type;
        if ($start != null && $end != null){
            $logs = Log::where('type',$type)
            ->whereDate('created_at','>=',$start)
            ->whereDate('created_at','<=',$end)
            ->orderBy('created_at','desc')
            ->paginate(16);
           //注意这里,需要为翻页加上搜索条件
            $logs->appends(['start' => $start,'end' => $end,'type' => $type]);
            return view('log.index',compact('logs'));
        }
        $logs = Log::paginate(16);
        return view('log.index',compact('logs'));
    }

多谢各位大佬,特别感谢
@王大牛 这个是新版里更简洁的方法 我的是5.3 只能用老的 appends()

paginate(config('page.num'))->withQueryString()

特别感谢 @23tl 是你的链接解决了问题

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!