garrynacov's avatar

How to limit in pagination in laravel ?

how to query for pagination limit in laravel ?

0 likes
4 replies
MichalOravec's avatar

You mean for example that you have 10000 rows in the database but you want to show only latest 300 rows and paginate them?

If so, you need to make normal query and then just paginate on a collection.

Create this service provider where you create a macro for pagination on a collection.

<?php

namespace App\Providers;

use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Illuminate\Support\ServiceProvider;

class ExtendCollectionServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        Collection::macro('paginate', function ($perPage, $total = null, $page = null, $pageName = 'page') {
            $page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);

            return new LengthAwarePaginator($this->forPage($page, $perPage), $total ?: $this->count(), $perPage, $page, [
                'path' => LengthAwarePaginator::resolveCurrentPath(),
                'pageName' => $pageName,
            ]);
        });
    }
}

Then you can use it like

$users = User::latest()->limit(300)->get();

$users->paginate(30); // here is pagination on a collection
6 likes
tykus's avatar

Your question is not clear - what do you mean to query for pagination limit?

1 like
garrynacov's avatar

thank you everyone.sorry yesterday did not share my code but the problem is over thanks to laracast and team.it's also my first time as a programmer so there's still a lot to fix thanks to everything @michaloravec @tykus

Please or to participate in this conversation.