简体   繁体   English

如何使用Laravel Collections实现分页?

[英]How to Implement Pagination with Laravel Collections?

As far as I know that Laravel pagination doesn't work with Laravel collections (Eloquent). 据我所知,Laravel分页不适用于Laravel集合(口才)。 For example: 例如:

$articles = Article::with('category')->where('status', 'submitted')->get();

I'm trying to make pagination with above code snipped but where('status', 'submitted') is not working. 我正在尝试使用上面的代码进行分页,但是where('status', 'submitted')无法正常工作。

Controller 调节器

$articles = Article::paginate(10);

Blade

@foreach($articles->with('category')->where('status', 'submitted') as $article)
    { ... }
    {{ $articles->links() }} 

I am getting an error. 我收到一个错误。

Paginate the query after your where clause: 在where子句后分页查询:

$articles = Article::with('category')->where('status', 'submitted')->paginate(10);

In your blade: 在刀片中:

{{ $articles->links() }}

@foreach($articles as $article)
    { ... }
@endforeach

Adding to @Remul's answer, if you still want to paginate a collection, you could do that with the forPage() method. 添加到@Remul的答案中,如果您仍然想对集合进行分页,则可以使用forPage()方法进行。 For example: 例如:

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);

$chunk = $collection->forPage(2, 3); 
// first argument is the page number 
// second one is the number of items to show per page

$chunk->all();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM