Search code examples
laravelcontrollermiddleware

How to execute code on every page load on laravel


I need to prepare a set of dates and store them in Session variables when the user reloads the page. This is done from the Controller. This is a problem because the app calls about 18 different controllers on each load, so I need to change the way these dates are stored.

I've thought about using a middleware but that would mean setting this middleware for each method where I load the view, otherwise it would still be loading this dates 18 times per call. Also I've tried setting a rate limiter of one minute, but the reason I have to change the way this is done is because the dates mix up on successive calls, and this idea prevented that happening more than once a minute.

So I was wondering if there was a way of calling a method just once per view load or something aprox.


Solution

    1. Create a new Service Provider:
    php artisan make:provider DateServiceProvider
    
    1. Open config/app.php and add your service provider to the providers array:
    'providers' => [
        // ...
        App\Providers\DateServiceProvider::class,
    ],
    
    1. In the newly created DateServiceProvider, use the boot method to set up your dates:
    namespace App\Providers;
    
    use Illuminate\Support\ServiceProvider;
    use Session;
    
    class DateServiceProvider extends ServiceProvider
    {
        /**
         * Bootstrap services.
         *
         * @return void
         */
        public function boot()
        {
            if (!Session::has('dates')) {
                // Calculate your dates here...
                $dates = '...';
    
                // Store the dates in session
                Session::put('dates', $dates);
            }
        }
    
        /**
         * Register services.
         *
         * @return void
         */
        public function register()
        {
            //
        }
    }
    

    Now, you can access these dates from any controller, middleware, or view via the session:

    $dates = session('dates');