8

I'm building a PHP app using Laravel Framework. I need to read some session values on every request and use this values on my controller methods.

How can I achieve this? Where to put this code?

I would like something like the Zend Framework Bootstrap class.

1
  • 1
    You can use Config::set('foo' => 'bar') in a service provider and Config::get('foo') will be available everywhere. If you use multidimensional arrays to set the values, you can grab them with dot notation. Commented Aug 5, 2015 at 2:46

2 Answers 2

4

The best practice is to use the Laravel Request Lifecycle (https://laravel.com/docs/8.x/lifecycle)

Following the documentation, the best place to place "onLoad" or global code, is on the boot method of the appServiceProvider. For example, if I wan't to set an specific timezone for all my project:

//app/Providers/AppServiceProvider.php
/**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        date_default_timezone_set('America/Argentina/Jujuy');
    }
Sign up to request clarification or add additional context in comments.

Comments

3

So, you can create a file named, for instance, BaseController.php which extends Controller. Then put your logic in the __construct()

Then, all of your other controllers can extend BaseController and in their __construct() they can perform a parent::__construct(); to make that fire.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.