Gabotronix's avatar

Automatically build laravel pagination object

Hi everybody, in my app each time I retrieve paginated results from the database I have to do somethig like this:

$posts = Post::latest()->with(['category','user'])->paginate($request->input('paginate', 6));
		
        $posts = 
        [
            'data' => $posts,
            'pagination' => [
                'total' => $posts->total(),
                'per_page' =>$posts->perPage(),
                'current_page' => $posts->currentPage(),
                'last_page' => $posts->lastPage(),
                'from' => $posts->firstItem(),
                'to' => $posts->lastItem()
            ] 
        ];

As you see I first retrieve the results from database and then I have to manually create the paginated data array, always doing the same seems bad and tedious to me honestly, I was wondering if there is a laravel magic method to automatically build the pagination payload array?

0 likes
2 replies
jlrdw's avatar
jlrdw
Best Answer
Level 75

Have you tried:

Post::latest()->with(['category','user'])->paginate(6);

Somethig like that, I don't know your data.

MichalOravec's avatar

Why do you do that?

With this you get same result.

$posts = Post::latest()->with(['category','user'])->paginate($request->input('paginate', 6));

In view

{{ $posts->withQueryString()->links() }}

Please or to participate in this conversation.