Skip to content

Instantly share code, notes, and snippets.

@leecolarelli
Created March 14, 2024 09:48
Show Gist options
  • Select an option

  • Save leecolarelli/f4d7bc8e68a68d482ae04754a114f98e to your computer and use it in GitHub Desktop.

Select an option

Save leecolarelli/f4d7bc8e68a68d482ae04754a114f98e to your computer and use it in GitHub Desktop.
My default Laravel AppServiceProvider
<?php
namespace App\Providers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Illuminate\Support\ServiceProvider;
final class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
$this->paginateCollection();
Model::shouldBeStrict( ! $this->app->isProduction());
}
/**
* Paginate a standard Laravel Collection.
*
* @return void
*/
public function paginateCollection(): void
{
/**
* Paginate a standard Laravel Collection.
*
* @param int $perPage
* @param int $total
* @param int $page
* @param string $pageName
* @return array
*/
Collection::macro('paginate', function ($perPage, $total = null, $page = null, $pageName = 'page'): LengthAwarePaginator {
$page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
/** @var Collection $this */
return new LengthAwarePaginator(
$this->forPage($page, $perPage)->values(),
$total ?: $this->count(),
$perPage,
$page,
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment