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
Another way as following:
in composer.json file, add the directives like this:
You can create a file named paths.php in root directory/config/paths.php
Insert this data into paths.php
Note : make sure to run command :
php artisan config:clear
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 itconstants.php
In there you have to return an array of config values.
And you can access them as follows
In addition to Arun Singh's answer I would recommend you to use helpers.
Inside your
helper.php
you may defineThus instead of
you may call
First you make
Constants
folder inside your app directory.And then you make
Constants.php
. Define your constants in this fileFor Example :
And you modify the
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:
And update your composer !
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.