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:

function getLanguage() {
    session('lang') ? session('lang') : 'en';
}
$LANG = getLanguage();

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

myModel::all($LANG);

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

<div> User language: {{$LANG}}</div>

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
public function handle(Request $request, Closure $next)
{
    Config::set('some-name.some-sub-name', session('lang') ?: 'en');

    return $next($request);
}
  • 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