简体   繁体   English

Laravel 5.3过滤后的链分页

[英]Laravel 5.3 chain paginate after filter

$posts = Post::all()->filter(function($item) use (&$pYear){
    return Persian::jDate(...) == $pYear;
})->sortByDesc('id')->paginate(5);

When I chain paginate(5), I get this error "Method paginate does not exist.", How can I paginate my result, please help, thank you. 当我链接paginate(5)时,出现此错误“方法paginate不存在。”,我如何对我的结果进行分页,请帮忙,谢谢。

Finally I solved it by creating a custom paginator of my collection, Maybe this is not the best way, I couldn't find a shorter solution, anyway my code works fine now. 最后,我通过创建我的收藏夹的自定义分页器解决了它,也许这不是最好的方法,我找不到更短的解决方案,无论如何我的代码现在都可以正常工作。

use Illuminate\Pagination\LengthAwarePaginator;

protected $perPage = 5;

$posts = Post::get()->filter(function($item) use (&$pYear){
    return Persian::jDate(...) == $pYear;
})->sortByDesc('id');

//this code simulates: ->paginate(5)
$posts = new LengthAwarePaginator(
         $posts->slice((LengthAwarePaginator::resolveCurrentPage() *
         $this->perPage)-$this->perPage,
         $this->perPage)->all(), count($posts),
         $this->perPage, null, ['path' => '']);
 

Try removing all() 尝试删除all()

$posts = Post::filter(function($item) use (&$pYear){
    return Persian::jDate('Y', strtotime($item->created_at),'','Asia/Tehran','en') == $pYear;
})->sortByDesc('id')->paginate(5);

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

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