Level 75
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