when i try to paginate results passed from the logged in user I get the error:
$message = Auth::user()->Notifications()->orderBy('created_at', 'desc')->get()
->groupBy(function($date) {
return Carbon::parse($date->created_at)->format('M d'); // grouping by day
})
->paginate(2);
Call to undefined method Illuminate\Database\Eloquent\Collection::paginate()
what is the problem and how can I paginate my object array?
Try this:
$message = Auth::user()->Notifications()->orderBy('created_at', 'desc')
->groupBy(function($date) {
return Carbon::parse($date->created_at)->format('M d'); // grouping by day
})->paginate(2);
the paginate method needs to be the last element in the chain like->get()
// edit: As stated here: http://laravel.com/docs/4.2/pagination
Note: 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 manually and use Paginator::make.
This could also be helpful: http://www.jenssegers.be/blog/57/laravel-pagination-with-grouping-and-eager-loading
Of course you get the error as groupBy
returns an instance of Illuminate\Support\Collection
. You would need to do something like
$messages = Auth::user()->Notifications()->orderBy('created_at', 'desc')->paginate(2);
$messages->setItems($messages->groupBy(function($date) {
return $date->created_at->format('M d'); // grouping by day
}));
This way you set up new items in your pagination object which are grouped results from database.