1
$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.

P9Q
  • 333
  • 4
  • 13

2 Answers2

3

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' => '']);
 
P9Q
  • 333
  • 4
  • 13
  • this is either an outdated method or just doesn't work. Method Algolia\ScoutExtended\Builder::slice does not exist. – Tim Bogdanov May 08 '23 at 15:40
0

Try removing all()

$posts = Post::filter(function($item) use (&$pYear){
    return Persian::jDate('Y', strtotime($item->created_at),'','Asia/Tehran','en') == $pYear;
})->sortByDesc('id')->paginate(5);
Seva Kalashnikov
  • 4,262
  • 2
  • 21
  • 36
  • Call to undefined method Illuminate\Database\Query\Builder::filter() – P9Q Oct 10 '16 at 16:39
  • You might better make it work with `->where` closure instead of `filter` – Seva Kalashnikov Oct 10 '16 at 16:43
  • I need a code similar to this but this does not work! `$posts = Post::where(Persian::jDate('Y', strtotime('created_at'),'','Asia/Tehran','en'), $pYear);` – P9Q Oct 10 '16 at 16:54