Laravel Eloquent获取最新记录报错latest()未找到,需实现DailyReport分页查询
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 calledget(), you can't uselatest()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 callingget()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:
latest()adds an order clause to the query (sorts by thecreated_atcolumn in descending order by default—you can pass a custom column likelatest('updated_at')if needed).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

