Ad

Laravel - Need To Access A Global Variable Set In BaseController From Within A Model

- 1 answer

I am creating a change logging system for replicating changes made to a table. This function essentially uses the beforeUpdate() hook, and allows me to make a copy of the old data in the ChangeLog for that table. I also want to tag it with some specific information such as the IP address making the request, and the user ID that made the request.

The user id is stored in a global variable inside of the BaseController class, which is accessible to any controller using $this->userId, however, I do not want to have to explicitly pass in that user id to every model call, so I would like to be able to access the $this->userId from with my various models, but laravel models apparently don't let you talk to the controller that way by just referencing $this->userId.

Can anyone give me an idea how to go about this? I've been digging for hours and can't find anything that does what I need?

Thanks so much, Wade

Ad

Answer

Basically if you don't want to pass the dependency you have two ways:

1 - Use session: you could store the ID in the session and get it wherever you want

2 - Create a service provider or a class to store the data you want and retrieve it later using the app Registry:

To do that you can create a class to store your data, then bind the instance on the service container:

$service = new ServiceClass( $id );  //this will contain the data you need: i.e the ID

$app->instance('your_key', $service);  //store the instante in the IoC Container 

Now you can get back the instance wherever you want with:

$service = $app->make('your_key');

and you could also create a Facade to access it

As a final note: code written in this way smells like 'bad global stuff' so you should consider passing the dependecy along to your models as long as you can

Ad
source: stackoverflow.com
Ad