skip to Main Content

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.

2

Answers


    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' => [
        // ...
        AppProvidersDateServiceProvider::class,
    ],
    
    1. In the newly created DateServiceProvider, use the boot method to set up your dates:
    namespace AppProviders;
    
    use IlluminateSupportServiceProvider;
    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');
    
    Login or Signup to reply.
  1. In Laravel, you can execute a method just once per view load by using the @once directive provided by Blade, Laravel’s templating engine. This directive ensures that the code within it is only executed once for each view rendering. Here’s how you can use it:

    @once
        <?php
            // Call your method here
            myMethod();
        ?>
    @endonce
    

    If I understood it right this is what you want.

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