How to Register Global Variables in Laravel

One of the benefits of using Laravel is the possibility to globally register and use a php file within our application, in this case, we are going to use that functionality to register variables that can be used anywhere in our code.

Create Variable File

As we saw in the post ¿How to register global methods in Laravel? we are going to create a php file with our variables in the path app/Helpers/variables.php so that later we can register that path in the composer.json

<?php const VARIABLE_1 = "Hello"; const VARIABLE_2 = 25; ...
Variables File Example

Register Variables

Similarly, in the composer.json we are going to add the path of our file inside the files attribute.

{ "autoload": { "files": [ "app/Helpers/variables.php" ] }, }
Register Variables File in composer.json

Suggestions

Although you can register any type of variable, it is recommended to only use simple values such as string, integer, float, etc in a similar way to .env and avoid objects or classes that can be separated into independent files.