【问题标题】:How to Implement Pagination with Laravel Collections?如何使用 Laravel 集合实现分页?
【发布时间】:2019-01-14 13:58:26
【问题描述】:

据我所知,Laravel 分页不适用于 Laravel 集合(Eloquent)。例如:

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

我正在尝试用上面的代码进行分页,但where('status', 'submitted') 不起作用。

控制器

$articles = Article::paginate(10);

刀片

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

我收到一个错误。

【问题讨论】:

  • 在分页子句之前添加 with/where。基本上,获取第一段代码,然后用 get 换取分页。
  • 您遇到的错误是什么?

标签: php laravel eloquent laravel-collection laravel-pagination


【解决方案1】:

在 where 子句之后对查询进行分页:

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

在你的刀片中:

{{ $articles->links() }}

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

【讨论】:

  • 非常感谢。它奏效了,我明白在这种情况下该怎么做。
【解决方案2】:

添加到@Remul 的答案,如果您仍想对集合进行分页,您可以使用forPage() 方法来实现。例如:

$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();

【讨论】:

    猜你喜欢
    • 2020-02-04
    • 2019-04-14
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 2013-02-20
    • 2021-04-18
    • 2015-09-30
    • 2015-06-06
    相关资源
    最近更新 更多