过滤后的Laravel 5.3链分页

时间:2016-10-10 16:21:51

标签: php laravel

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

当我链接paginate(5)时,我收到此错误“方法paginate不存在。”,我如何分页我的结果,请帮助,谢谢。

2 个答案:

答案 0 :(得分:1)

最后我通过创建我的集合的自定义分页器来解决它,也许这不是最好的方法,我找不到更短的解决方案,无论如何我的代码现在工作正常。

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' => '']);
 

答案 1 :(得分:0)

尝试删除all()

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