Laravel Collection paginate does not exist

Viewed 464

I'm trying to implement basic pagination when retrieving notifications, but I get the following error.

Method Illuminate\Notifications\DatabaseNotificationCollection::paginate does not exist.

public function index()
{
    $messages = collect();
    $notifications = auth()->user()->unreadNotifications->paginate(5);
    foreach ($notifications as $notification) {
        $message = NotificationToMessageFactory::make($notification->type)
            ->toMessage($notification->data);
        $messages->push($message);
    }
}
2 Answers

You've to call paginate() on query builder instance not on a collection. Correct syntax will be :

$notifications = auth()->user()->unreadNotifications()->paginate(5);

You should paginate before looping through the collection, otherwise you will be retrieving all records matching the query, when you only need 5. Like this:

$messages = collect();
$notifications = auth()->user()->unreadNotifications()->paginate(5);
 
foreach($notifications as $notification) {
    $message = NotificationToMessageFactory::make($notification->type)->toMessage($notification->data);
    $messages->push($message);   
}
Related