Monday, 15 April 2019

php - 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


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::get('constants.options');
// or if you want a specific one
Config::get('constants.options.option_attachment');


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...