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 mad
Another way as following:
in composer.json file, add the directives like this:
"autoload": {
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/helpers.php",
"app/config/constants.php"
]
}
i think best way to define constant using a helper file. check my solution.
Define file path in composer.json
"extra": {
"laravel": {
"dont-discover": []
}
},
"autoload": {
"files": [
"app/helpers.php",
"app/Helper/function.php" // constant defined here
],
app/Helper/function.php
define("assetPath","UI/");
define("viewPath","UI/");
use this constant anywhere in project. i am using in blade file.
<script src="{{asset(assetPath.'js/jquery.min.js')}}"></script>
<script src="{{asset(assetPath.'js/popper.min.js')}}"></script>
<script src="{{asset(assetPath.'js/bootstrap.min.js')}}"></script>
my approach is better than this
Config::get('constants.options');
Config::get('constants.options.option_attachment');
here another problem is this , you have to run cache:clear or cache command for this. but my approach not required this.
Your question was about the 'best practices' and you asked about the '.env method'.
.env is only for variables that change because the environment changes. Examples of different environments: test, acceptance, production.
So the .env contains database credentials, API keys, etc.
The .env should (imho) never contain constants which are the same over all environments. Just use the suggested config files for that.
You can simply do this:
Put your constants to 'config/app.php' on main array, like:
'CONSTANT_NAME' => 'CONSTANT_VALUE',
Use them where ever you want with:
{{ Config::get('CONSTANT_NAME') }}
require app_path().'/constants.php';
define('ADMIN', 'administrator');
or -
You can also move more sensitive info
return [
'hash_salt' => env('HASH_SALT'),
];
And use it like before:
echo Config::get('constants.hash_salt');
You can define constants at the top of the web.php file located in routes and can be access the constants anywhere in project with just constant name
define('OPTION_ATTACHMENT', 13);
define('OPTION_EMAIL', 14);
define('OPTION_MONETERY', 15);
define('OPTION_RATINGS', 16);
define('OPTION_TEXTAREA', 17);