Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

EdsonOrdaz's avatar

use global variable

hello, how can I use a variable that works in all my controllers?

When I start the session, I want to store variables from the database, so that every time I open a controller I can read them without having to go looking for them again in the database.

I can't do it with a config.php file since I need to use the variable per session.

0 likes
1 reply
LaryAI's avatar
Level 58

One solution is to use Laravel's global helper function config(). You can define your variables in a configuration file and then access them from any controller using config(). Here's an example:

  1. Create a new configuration file in the config directory, e.g. myconfig.php.
  2. Define your variables in the configuration file, e.g.:
return [
    'my_variable' => 'my_value',
    'another_variable' => 'another_value',
];
  1. In your controller, you can access the variables using config():
$myVariable = config('myconfig.my_variable');
$anotherVariable = config('myconfig.another_variable');

Note that you can also use the config() function to set values dynamically, e.g.:

config(['myconfig.my_variable' => 'new_value']);

This will update the value of my_variable in the configuration file.

Please or to participate in this conversation.