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

Laravel API分页报错:Method Illuminate\Database\Eloquent\Collection::paginate不存在

问题解决:Laravel API分页报错 Method Illuminate\Database\Eloquent\Collection::paginate does not exist

错误原因

你调用了get()方法,这个方法会立即执行SQL查询并返回Eloquent集合对象,而paginate()是Laravel查询构建器(Query Builder)的方法,只能在未执行查询的构建器实例上调用,集合对象没有这个方法,所以触发报错。

修正后的代码

直接去掉get(),让paginate()作用在查询构建器上即可:

public function index()
{
    $posts = Post::with('comment', 'user')
        ->latest()
        ->paginate(5);
    return response()->json([
        'status'=>200,
        'posts'=>$posts
    ]);
}

补充说明

  • latest()默认按created_at字段倒序排序,刚好满足你“按最新排序”的需求
  • paginate(5)会自动处理分页逻辑,返回的结果包含current_page、last_page、per_page等分页元数据,前端可直接用这些参数实现分页导航

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 06:35:48