Laravel Method paginate does not exist

…衆ロ難τιáo~ 提交于 2020-12-27 08:47:14

问题


I am trying to paginate Model result, but I am getting "Method paginate does not exist.". Here is my code:

$user_dispatches = Dispatch::all()->where('user_id', Auth::id())->paginate(10);

I need to get all records where users id equals current authenticated users id. Works well without paginate() method.


回答1:


You need to remove all():

Dispatch::where('user_id', Auth::id())->paginate(10);

When you're using all() you get all the rows from the table and get a collection. Then you're using collection method where() (and not Query Builder method where()) and then you're trying to use paginate() method on the collection and it doesn't exist.




回答2:


Extending a bit Alexey's perfect answer :

Dispatch::all() => Returns a Collection

Dispatch::all()->where() => Returns a Collection

Dispatch::where() => Returns a Query

Dispatch::where()->get() => Returns a Collection

Dispatch::where()->get()->where() => Returns a Collection

You can only invoke "paginate" on a Query, not on a Collection.

And yes, it is totally confusing to have a where function for both Queries and Collections, working as close as they do, but it is what it is.




回答3:


for use all recorde and pagination , you need use below code :

$user_dispatches = Disspath::paginate(8);



回答4:


You need remove method all() :

$user_dispatches = Dispatch::where('user_id', Auth::id())->paginate(10);

Because all() return a Collection while paginate() used a Builder




回答5:


Dispatch::where('user_id', auth()->user()->id)->paginate(10);


来源:https://stackoverflow.com/questions/48148472/laravel-method-paginate-does-not-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!