Skip to content
Advertisement

Make a variable available in all controllers

I am not sure the title of the question is clear, so I will try to explain it in details.

I want to execute a piece of code in every controller automatically, assign the result to a variable that will be globally accessible everywhere.

So the code that need to be run will be like this:

JavaScript

In any controller I need to access that variable like this:

JavaScript

Also in the view, it would be helpful to access that variable as well (if possible)

JavaScript

Is there any place where I can execute that piece of code automatically?

Advertisement

Answer

  • Create a middleware
  • Add new middleware to AppHttpKernels $middleware property, if you want it to run on every request. You may also put into $middlewareGroups property’s web key.
  • Your middleware’s handle method will be like this
JavaScript
  • You will be updating a config in your middleware. This config has to be set only in this middleware to prevent possible problems of shared global state. (it is also important to be unique)
  • Then you can use it with config('some-name.some-sub-name')
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement