Laravel 5.6 - 全局和动态变量

I have an API with laravel 5.6 and I need to create global variables that throughout the application can have their value changed, however I am having problems.

Example: - At the first request, the value of this variable as "test"; - In the second request I want to get the current value, which should be "test";

  1. I tried initially to use the config, but it did not work;
  2. I tried to use Session, but I had the same problem;
  3. I tried to set a variable in the "super controller", where all controllers extended to it, it did not work.

The value of the variable is only valid during the execution of the request, that is, I make a request to the controller aaaControler, this makes use of other controllers, within the same request the value persists, but ends in the return.

I thought of persisting in the database, creating a reference and always fetching this value there, but will this be the best way?

I ask for help in this matter.

Thank you.

If you need to have a "global" variable just for one request, accessible in every class of your project, I think a good solution is to set a config value at runtime. The config helper can be used both for reading as writing a value that will not persist on another request.

You can set a value wherever you want:

config(['any.key.you.want' => 'Some value']);

And read it everywhere:

config('any.key.you.want');
=> 'Some value'

This works fine if you use the other controllers by instantiating it and calling its methods (what I think is not good for your code organization – you should probably use a service class).

If you use other controllers using HTTP requests, it will not work. If this is your case, probably the best solution is to persist it to the database – as you proposed – or to use session. You store the value using one of these and then clear after your HTTP requests:

session()->put('any.key.you.want', 'Some value');
// make http request to another controller
session()->forget('any.key.you.want');

In the controller called by the HTTP request, you can get a session value:

session('any.key.you.want');
=> 'Some value'

If your HTTP request is async, you will probably run into some race conditions.

The fact is that your every API request is a completely new request, going through a full cycle from index.php to the JSON(or other)-response. In order to save a variable between essentially different requests, you will have to use a database, file storage or sessions(with some notes).