What is the best practice for adding constants in laravel? (Long List)

Faran Khan picture Faran Khan · Feb 10, 2017 · Viewed 73.4k times · Source

I am rather new to laravel. I have a basic question, What is the best way to add constants in laravel. I know the .env method that we use to add the constants. Also I have made one constants file to use them for my project. For example:

define('OPTION_ATTACHMENT', 13);
define('OPTION_EMAIL', 14);
define('OPTION_MONETERY', 15);
define('OPTION_RATINGS', 16);
define('OPTION_TEXTAREA', 17);

And so on. It can reach upto 100 or more records. So What should be the best approach to write the constants. The .env method. Or adding the constant.php file?

Thanks

Answer

K Arun Singh picture K Arun Singh · Feb 10, 2017

For most constants used globally across the application, storing them in config files is sufficient. It is also pretty simple

Create a new file in the config directory. Let's call it constants.php

In there you have to return an array of config values.

return [
    'options' => [
        'option_attachment' => '13',
        'option_email' => '14',
        'option_monetery' => '15',
        'option_ratings' => '16',
        'option_textarea' => '17',
    ]
];

And you can access them as follows

Config::get('constants.options');
// or if you want a specific one
Config::get('constants.options.option_attachment');