skip to Main Content

i can specify how many records to return on per page with the code :

$payments = Payment::paginate(10);

or, for example, i can do the same for users with the following code :

$users = User::paginate(10);

if tomorrow i want to change the number 10 to 50, a disaster will happen

how can i change this number globally in setting? (the more flexible and better structured the code is, the happier i am 🙂 )

i had many attempts

like creating pagination.php file in path app/config with the following content :

<?php

return [
    'per_page' => 1,
];

or change file AppServiceProvider.php to following content:

<?php

namespace AppProviders;

use IlluminateSupportServiceProvider;
use IlluminatePaginationPaginator;


class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Paginator::perPage(1);
    }
}

2

Answers


  1. As far as I know, there is no way to globally set the pagination number. Just creating a config setting without doing anything else does not work, as you noticed.

    However, if you create a new config file called config/pagination.php with the following:

    <?php
    
    return [
        'per_page' => 1,
    ];
    

    Then, you can use the following:

    $payments = Payment::paginate(config('pagination.per_page'));
    $users = User::paginate(config('pagination.per_page'));
    

    This allows you to globally set the pagination count!

    Login or Signup to reply.
  2. You can set .env variable for per page value and update it whenever you want.
    Firstly, create a pagination.php file in the config directory:

    return [
        'per_page' => env('PAGINATION_PER_PAGE', 15),
    ];
    

    usage of it:

    $payments = Payment::paginate(config('pagination.per_page'));
    $users = User::paginate(config('pagination.per_page'));
    

    in the .env:

    PAGINATION_PER_PAGE=10
    

    don’t forget to run php artisan config:clear for clearing caches.

    And you can simply change this variable by code: config(['pagination.per_page' => 50]);

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search