October 14th, 2016

How to Use Real Global Constants in Laravel

I've read several posts around the web suggesting the use of config variables as constants in Laravel. There's an issue with that: they are not real constants. They are variables. If you need to use real global constants in Laravel, there are a couple of ways you can load your own. Let me show you how I've done it.

First, create a file called constants.php inside the bootstrap folder of your Laravel application. Define your global constants in this file so they are all nice and cozy in one place. For example:

constants.php

<?php
define('COLOR_ONE', 'blue');
define('COLOR_TWO', 'red');

Now, there are a couple of ways you can load this file so that these constants are available for use throughout your application. These are in no particular order. You can choose whichever method you prefer.

Method 1: autoload.php

Modify the file bootstrap/autoload.php by adding the following code at the end of it:

<?php
...
...
//Load custom global constants.
require __DIR__.'/constants.php';

When you run your app, this line of code will load your bootstrap/constants.php file with all your constants as part of the Laravel bootstrapping sequence.

Method 2: composer.json

Alternatively, you can use composer.json to load the bootstrap/constants.php file by adding the following code to the "autoload" section, like so:

"autoload": {
    "files": [
        "bootstrap/constants.php"
    ]
}

Before this change can take effect, you must run the following command in Terminal to regenerate Laravel's autoload files:

cd path/to/your/project
composer dump-autoload

Once you run that command, your constants will be automatically loaded when you run your app.

That's all there is to it. It's not too difficult to define and load your own real global constants in Laravel.

Was this post useful? Any issues or questions? Let me know on Twitter.