[英]How to paginate in laravel? method paginate doesn't exist
Trying to get the latest task for each user, so if there is 100 users, I want to get only 10 to display per page but it won't work. 试图为每个用户获取最新任务,因此,如果有100个用户,我希望每页只显示10个,但它不起作用。 When adding the paginate method I get the following error: 添加paginate方法时,我收到以下错误:
Method Illuminate\\Database\\Eloquent\\Collection::paginate does not exist. 方法Illuminate \\ Database \\ Eloquent \\ Collection :: paginate不存在。
If I remove the method it all works fine, I get the results expected, I just want to paginate. 如果我删除方法它一切正常,我得到预期的结果,我只想分页。 This is my code: 这是我的代码:
$users = User::with('latestTask')->get()->paginate(10);
You need to call the method directly, without using get()
你需要直接调用方法,而不使用get()
$users = User::with('latestTask')->paginate(10);
and in your blade you can get the page links using 在您的刀片中,您可以使用页面链接
$variable_name->links()
You can not paginate a collection 您无法对集合进行分页
$users = User::with('latestTask')->get();
to paginate you should use method paginate() on Eloquent results: 要分页,你应该在Eloquent结果上使用方法paginate():
$users = User::with('latestTask')->paginate(10);
and then in view put the link : 然后在视图中放置链接:
{{ $users->links() }}
When you use paginate you then don't need to use get() . 当您使用paginate时,您不需要使用get() 。 just follow the the below code as well. 只需按照下面的代码。
$users = User::with('latestTask')->paginate(10);
User model will automatically handle the request and get number of data given as argument in paginate($number_of_rows)
method. 用户模型将自动处理请求并获取在paginate($number_of_rows)
方法中作为参数给出的数据数。
you can also use orderBy() in as method chaining format like below. 你也可以使用orderBy()作为方法链接格式,如下所示。
$users = User::with('latestTask')->orderBy($column,'asc')->paginate(10);
Although other answers are right, I wanted to point out the reason behind it... 虽然其他答案是正确的,但我想指出其背后的原因......
get()
executes the query and returns a collection which means you are no longer building/modifying the sql query get()
执行查询并返回一个集合,这意味着您不再构建/修改SQL查询
paginate()
should be called on the elequent query itself before it's executed so it can add to the query the offset and limit... paginate()
应该在执行之前在elequent查询本身上调用,这样它就可以向查询添加偏移和限制...
That's why it should be 这就是原因
$users = User::with('latestTask')->paginate(10);
You can see in the error that Illuminate\\Database\\Eloquent\\Collection
method paginate doesn't exist because paginate is not a part of the collection 您可以在错误中看到Illuminate\\Database\\Eloquent\\Collection
方法paginate不存在,因为paginate不是集合的一部分
Quoting laravel documentation https://laravel.com/docs/5.8/pagination 引用laravel文档https://laravel.com/docs/5.8/pagination
There are several ways to paginate items. 有几种方法可以对项目进行分页。 The simplest is by using the paginate method on the &query builder or an Eloquent query 最简单的方法是在&query构建器或Eloquent查询上使用paginate方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.