Wade
Wade

Reputation: 351

Laravel - Need to access a global variable set in BaseController from within a model

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

Upvotes: 2

Views: 664

Answers (2)

Moppo
Moppo

Reputation: 19285

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

Upvotes: 1

wupendra
wupendra

Reputation: 86

By creating scope you can get the userID value in your model. For example, in the article model if I want to check if the author of the article is the current user or not I can make my own scope as:

public function scopeUserid($query,$id){
    $query->where('user_id',$id);
}

In the controller you can pass the userID by

$allArticlesFromCurrentAuthor = Article::userid($this->userId)->get();

I hope it helps.

Upvotes: 1

Related Questions