Reputation: 33
I am on Laravel Framework version 5.1.45 (LTS).
One club can have many events. I am trying to list all the events, group them by year and show one page per year.
According to my Laravel version documentation "Currently, pagination operations that use a groupBy statement cannot be executed efficiently by Laravel. If you need to use a groupBy with a paginated result set, it is recommended that you query the database and create a paginator manually."
Here is my attempt to create the paginator manually and it seems to do the job:
public function index()
{
$page = Paginator::resolveCurrentPage() - 1;
$perPage = 1;
$events = new Paginator(Event::orderBy('date', 'desc')->groupBy(DB::raw('YEAR(date)'))->skip(($page - 1) * $perPage)->take($perPage + 1)->get(), $perPage, $page);
$events->setPath(['events/events']);
return view('events.index', ['events' => $events]);
}
And here is how I try to display the links at the bottom of the page.
{!! $events->render() !!}
If I remove the render bit, the page is displayed, albeit with no links. I can even go to the next page (year 2016) adding manually ?page=2 at the end of the url in my browser.
But if I leave the render bit in the index page, I get ErrorException in AbstractPaginator.php line 130: Array to string conversion.
What am I doing wrong?
Upvotes: 1
Views: 152
Reputation: 168
Hope this snippet can help
public function index(Request $request)
{
$posts = Post::all()
->paginate($request->get('per_page', 25));
$grouped_by_date = $posts->mapToGroups(function ($post) {
return [$post->published_date => $post];
});
$posts_by_date = $posts->setCollection($grouped_by_date);
return view('posts.index', compact('posts_by_date'));
}
Basically redefine the collection with the grouped collection.
Upvotes: 1