Skip to content
Advertisement

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

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

Advertisement

Answer

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('constants.options');
// or if you want a specific one
config('constants.options.option_attachment');
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement