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

Laravel Eloquent获取最新记录报错latest()未找到,需实现DailyReport分页查询

Fixing "latest() not found" Error When Paginating DailyReport Data

Hey there, let's get this sorted out right away! The error you're seeing happens because you're using the methods in the wrong order—here's why and how to fix it:

The Problem with Your Current Code

Your line DailyReport::get()->latest()->paginate(10) has a critical order issue:

  • get() immediately executes the query and returns an Eloquent Collection of all your DailyReport records.
  • The latest() method belongs to the Query Builder, not the Collection class—so once you've called get(), you can't use latest() anymore, hence the "not found" error.
  • On top of that, paginate() is also a Query Builder method that handles executing the query and returning paginated results, so calling get() first makes it redundant anyway.

The Correct Approach

You want to chain the methods in the order that builds the query first, then executes it with pagination. Here's the fixed code:

DailyReport::latest()->paginate(10);

This does exactly what you need:

  1. latest() adds an order clause to the query (sorts by the created_at column in descending order by default—you can pass a custom column like latest('updated_at') if needed).
  2. paginate(10) executes the query, fetches the first 10 records, and returns a pagination instance with all the necessary metadata (total records, links, etc.).

If you don't need the sorting and just want paginated results of all records, you can simplify it to:

DailyReport::paginate(10);

Quick Recap

Always remember: Query Builder methods (like latest(), where(), orderBy()) need to come before execution methods (like get(), paginate(), first()). Execution methods convert the query into a collection or model, and you can't use Query Builder methods on those results.

内容的提问来源于stack exchange,提问作者B L Praveen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:55:31