proper use of Laravel's paginate method?

笑着哭i 提交于 2021-02-10 03:08:30

问题


When I use the paginate method with the following statement:

$user = User::where('id', 1)->first();
$images = $user->images->paginate(3);

I get the following error:

Method Illuminate\Database\Eloquent\Collection::paginate does not exist

However when I call it with the following statement:

$images = Image::where('user_id', $user->id)->paginate(3);

It works accordingly... I'm fairly new to Laravel, so forgive my ignorance, but what is the cause of the difference in results? Don't both statement return collections?


回答1:


paginate is a method of the query builder not the collection. If you want to paginate the collection you need to do manual pagination:

$imagesPage = new LengthAwarePaginator($user->images->forPage($page,3), $user->images->count(), 3, $page); //Where $page is the current page number

Alternatively you can paginate the query builder:

$images = $user->images()->paginate(3); 

Note that if you use the 2nd approach you don't need to eager load the images.



来源:https://stackoverflow.com/questions/50226653/proper-use-of-laravels-paginate-method

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