Reputation: 1593
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 up to 100 or more records. So what should be the best approach to write the constants? The .env method? Or adding the constant.php file?
Upvotes: 119
Views: 181313
Reputation: 115
You can create a file named Constants.php in root directory /app/Constants/Constants.php
Edit composer.json:
....
"autoload": {
....
"files": [
"app/Constants/Constants.php"
]
},
....
Insert this data into Constants.php
define('HTTP_STATUS', 'httpStatus');
define('HTTP_MESSAGE', 'message');
define('HTTP_SUCCESS', 'Success');
define('HTTP_STATUS_OK', '200');
define('HTTP_STATUS_NOT_FOUND', '404');
define('HTTP_STATUS_BAD_REQUEST', '400');
define('HTTP_STATUS_SERVER_ERROR', '500');
Note : run command :
composer update
Upvotes: 0
Reputation: 29039
I think you should not have a single place for all your constants. Especially no file called constance.php
.
I use PHP constance in classes and refer to them in code, so its more readable, typically to avoid magic numbers and typos in strings
Car::where('car_type','=', 'fast_car')->get();
and rather have
Car::where('car_type','=', CarType::FAST)->get();
If its a value that depends on your environment (like email setting, should be different local vs production), then you should add it to a matching files in the config folder (e.g. '/config/mail.php'). You may also just add a new file in the config folder. A config file returns an array, so it could look like this:
<?php
return [
'your_option' => env('YOUR_OPTION')
];
and you can read it using the config helper:
config('your_config_file.your_option');
Its important to never call the env
function outside a configuration file, as the env function returns null outside a configuration file when cache is enabled.
If the option does not rely on your environment, you can just add it directly to the matching config file.
<?php
return [
'your_option' => 10
];
Upvotes: 14
Reputation: 363
I would personally create a class for that.
<?php
namespace App\Transaction\Constants;
/**
* Class TransactionTypeConstant.
*/
final class TransactionTypeConstant
{
public const TYPE_CREDIT = 'CREDIT';
public const TYPE_DEBIT = 'DEBIT';
}
and use it like this:
<?php
namespace App\Transaction;
use App\Transaction\Constants\TransactionTypeConstant;
class Transaction
{
/**
* Execute the task.
*
* @return object
*/
public function run()
{
if ($transaction->type === TransactionTypeConstant::TYPE_DEBIT) {
//do something
}
}
}
Upvotes: 14
Reputation: 1906
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.
Upvotes: 0
Reputation: 307
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') }}
Upvotes: 2
Reputation: 270
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');
Upvotes: 0
Reputation: 825
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);
Upvotes: 2
Reputation: 179
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"
]
}
Upvotes: 11
Reputation: 454
You can create a file named paths.php in root directory/config/paths.php
Insert this data into paths.php
define('OPTION_ATTACHMENT', 13);
define('OPTION_EMAIL', 14);
define('OPTION_MONETERY', 15);
define('OPTION_RATINGS', 16);
define('OPTION_TEXTAREA', 17);
Note : make sure to run command : php artisan config:clear
Upvotes: 18
Reputation: 2038
I use aliased class constants :
First, create your class that contain your constants : App/MyApp.php
for exemple
namespace App;
class MyApp {
const MYCONST = 'val';
}
Then add it to the aliased classes in the config/app.php
'aliases' => [
//...
'MyApp' => App\MyApp::class,
Finally use them wherever you like (controllers or even blades) :
MyApp::MYCONST
Upvotes: 128
Reputation: 1813
First you make Constants
folder inside your app directory.
And then you make Constants.php
. Define your constants in this file
For Example :
define('ONE', '1');
define('TWO', '2');
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:
"autoload": {
"files": [
"bootstrap/constants.php"
]
}
And update your composer !
Upvotes: 19
Reputation: 846
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.
Upvotes: 22