Reputation: 593
I have two models : Task and Comment
In my user profil I want to display tasks and comments sort by created date.
For this I do :
$timeline_array = $customer->comments;
$timeline_array = $timeline_array->toBase()->merge($customer->tasks);
//sort timeline event
$timeline_array = $timeline_array->sortByDesc(function($timeline_event){
return $timeline_event->created_at;
});
And I foreach my array in my view. It's work fine but if I have too much comments or tasks it's will be a big request so I want to add a paginator.
How can I do it ?
If I had a $timeline_array->paginate(5);
at the end I get the error :
Method Illuminate\Support\Collection::paginate does not exist.
And I think it's not fixing my problem because I load all the comments and tasks before I paginate it.
Somebody have an idea/solution ?
Upvotes: 0
Views: 1435
Reputation: 593
Finally found a solution :
$timeline_array = $customer->comments;
$timeline_array = $timeline_array->toBase()->merge($customer->tasks);
//sort timeline event
$timeline_array = $timeline_array->sortByDesc(function($timeline_event){
return $timeline_event->created_at;
});
$item_per_page = 10;
$timeline_array = new LengthAwarePaginator($timeline_array->forPage(Paginator::resolveCurrentPage(), $item_per_page), count($timeline_array), $item_per_page, Paginator::resolveCurrentPage(), [
'path' => Paginator::resolveCurrentPath()
]);
Upvotes: 4
Reputation: 917
Paginate method only works on a query builder or an eloquent , someone has created a gist over here where you can use paginate over an array or collection :
https://gist.github.com/vluzrmos/3ce756322702331fdf2bf414fea27bcb
Try using it like this :
$timeline_array = $customer->comments;
$timeline_array = $timeline_array->toBase()->merge($customer->tasks);
//sort timeline event
$timeline_array = $timeline_array->sortByDesc(function($timeline_event){
return $timeline_event->created_at;
});
$timeline_array = $this->paginate($items);
public 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);
}
Or adding it as a Macro for collection in your App Service Provider for more better practice.
Upvotes: 0