How to Use Real Constants in Laravel

Mario - Jan 11 '18 - - Dev Community

I’ve read several posts around the web suggesting the use of config variables as constants in Laravel. The issue I see with that, is that those are not real constants. They are variables. If you need to use real constants in Laravel, there are a couple of ways you can load your own constants. Let me show you how I get it done.

First, create a file called constants.php inside the bootstrap folder of your Laravel application. Define your 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');
Enter fullscreen mode Exit fullscreen mode

Now, there are a couple of ways you can load this file so that the 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 constants.
require __DIR__.'/constants.php';
Enter fullscreen mode Exit fullscreen mode

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"
    ]
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 constants in Laravel.

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

. . . . . . . . . . . .