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

Laravel 8自定义分页实现:按发布日期分页并移除desc_id列

问题解决:Laravel 8手动实现分页(无需paginate)并移除desc_id列

问题分析

你的代码返回空$articles的核心原因:

  • 查询构造器$articles_show未执行get(),直接遍历无法获取数据库数据
  • 排序字段写错:publicated_at应为需求中的publication_date
  • 依赖已移除的desc_id做分页筛选,逻辑完全失效

修正后的控制器代码

public function pages($id = null)
{
    // 每页展示数量
    $perPage = 8;
    // 获取当前页码,默认第1页
    $thisPage = $id ? (int)$id : 1;
    // 计算偏移量:(当前页-1)*每页数量
    $offset = ($thisPage - 1) * $perPage;

    // 构建查询:筛选已发布文章,按publication_date倒序
    $articles = Article::where(function ($query) {
            $query->where('draft', 0)
                  ->where(function ($subQuery) {
                      $subQuery->whereNull('publication_date')
                               ->orWhere('publication_date', '<=', DateHelper::currentDateTime());
                  });
        })
        ->orderBy('publication_date', 'DESC')
        ->skip($offset)
        ->take($perPage)
        ->get();

    // 计算总文章数(用于分页导航,可选)
    $totalArticles = Article::where(function ($query) {
            $query->where('draft', 0)
                  ->where(function ($subQuery) {
                      $subQuery->whereNull('publication_date')
                               ->orWhere('publication_date', '<=', DateHelper::currentDateTime());
                  });
        })->count();
    
    // 给文章添加全局行号(替代原desc_id的作用)
    $articles = $articles->map(function ($article, $index) use ($offset) {
        $article->row_number = $offset + $index + 1;
        return $article;
    });

    return view('allArticles.page'.$thisPage)
        ->with('articles', $articles)
        ->with('this_page', $thisPage)
        ->with('total_pages', ceil($totalArticles / $perPage)); // 传递总页数用于分页导航
}

代码修改说明

  • 执行查询:给查询构造器添加get(),真正从数据库拉取数据
  • 修正排序字段:替换为需求指定的publication_date
  • 高效分页逻辑:用skip($offset)跳过前置数据,take($perPage)取当前页8条,避免全量查询后筛选的低效操作
  • 行号实现:通过map()基于偏移量+当前页索引计算全局行号,替代原desc_id的功能
  • 简化查询条件:优化嵌套闭包层级,减少冗余代码
  • 可靠页码处理:直接使用路由参数$id作为页码,比Request::segment(2)更稳定

视图调整(如需显示行号)

如果要在视图中展示行号,直接调用$article->row_number即可:

{{-- 示例:在标题前添加行号 --}}
<h2><span>#{{$article->row_number}}</span> <a href="{{url($article->permalink)}}">{{$article->h1}}</a></h2>

额外建议

  • 避免直接拼接视图名称allArticles.page'.$thisPage,页数过多会导致视图文件冗余,建议用单个视图接收页码参数渲染
  • 可基于total_pages变量生成上一页、下一页、页码跳转等分页导航元素

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 12:55:18