Shanediesel
Shanediesel

Reputation: 211

Laravel Collection paginate does not exist

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);
    }
}

Upvotes: 3

Views: 1299

Answers (2)

Nuno Peixoto
Nuno Peixoto

Reputation: 154

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);   
}

Upvotes: 1

Ahsan Zaman
Ahsan Zaman

Reputation: 91

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

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

Upvotes: 2

Related Questions