fonini
fonini

Reputation: 3341

Where to put a code to execute on every Laravel request?

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.

Upvotes: 8

Views: 1987

Answers (2)

JuliSmz
JuliSmz

Reputation: 1146

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');
    }

Upvotes: 4

Ohgodwhy
Ohgodwhy

Reputation: 50777

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.

Upvotes: 3

Related Questions