Reputation: 415
I have a news table and i manage the read or unread flag. so I want to paginate both flags are separate without additional database queries.
My requirement is to get all the news and filter read or unread and paginate for a separate table view.
Once I try the following code but getting an error Method Illuminate\Database\Eloquent\Collection::paginate does not exist.
$ns=News::all();
$ns->where('read',1)->paginate(2);
$ns->where('read',0)->paginate(2);
I want to do that using only one DB Query.
Upvotes: 0
Views: 1544
Reputation: 1212
Please try to add it to helpers
function paginate($items, $perPage = 15, $page = null, $options = []) {
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
$items = $items instanceof Collection ? $items : Collection::make($items);
return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
});
Usage:
$ns = News::all();
$ns1 = paginate((clone $ns)->where('read', 1), 2);
$ns2 = paginate((clone $ns)->where('read', 0), 2);
Upvotes: 0
Reputation: 81
Laravel paginate can't make a pagination from collection, you need eloquent query builder instead.
https://laravel.com/docs/7.x/pagination#paginating-query-builder-results
So, if you still want make a pagination from collection, you can create custom pagination for collection with macro. An example is in this gist :
https://gist.github.com/simonhamp/549e8821946e2c40a617c85d2cf5af5e
Upvotes: 1
Reputation: 290
Can you Try below code
$readns = News::where('read',1)->paginate(2);
$unreadns = News::where('read',0)->paginate(2);
You can use chunk() for it. Check this one laravel.com/docs/7.x/queries#chunking-results
Upvotes: 2