Reputation: 1431
As I checked on multiple sources, the Laravel way of defining constant variables is through config files. However, in my case, I want to use constants across my config files which is not possible since, as I read, it's not possible/advisable to call a config from another.
Constants:
define('THE_ID_OF_SOMETHING_NICE', 1);
define('THE_ID_OF_SOMETHING_UGLY', 2);
define('THE_ID_OF_SOMETHING_BAD', 12372);
config1.php
return [
THE_ID_OF_SOMETHING_NICE = ['many', 'nice', 'data'],
]
config2.php
return [
['many', 'nice', 'data', THE_ID_OF_SOMETHING_NICE],
]
As you can see, I just can't use the actual value of the defined constants since it'll be too unreadable. Also I don't want to clump up my .env file with these constants since it's not really meant for it.
Any workaround for this? Thanks.
P.S Why does this so hard whilst it should be very basic principle of PHP to utilise constant definitions. CI has these figured out :/
Upvotes: 2
Views: 2663
Reputation: 2806
I think you can use php include
on your config.php
if you don't want add a lot of to .env
file. Just like that
<?php
include 'something_constant.php';
return [
THE_ID_OF_SOMETHING_NICE = ['many', 'nice', 'data'],
];
Upvotes: 1
Reputation: 2355
The best way to do this is to add them to the config/app.php
file. Somewhere above the providers[] list you could add
'CONST' => ['THE_ID_OF_SOMETHING_NICE' => 1,
'THE_ID_OF_SOMETHING_UGLY' => 2,
],
and anywhere in the code access the values with the laravel helper config('app.CONST.THE_ID_OF_SOMETHING_NICE');
You can make use of the .env
file but beware that in production, this file is ignored because the config is automatically cached. In .env you could add the line THE_ID_OF_SOMETHING_NICE=1
and in the config/app.php
file you add
'CONST' => ['THE_ID_OF_SOMETHING_NICE' => env('THE_ID_OF_SOMETHING_NICE'),],
from where you can access the value just the same with the config()
helper.
Personally I add the values in the app.php
file and don't bother with adding values to .env, because mostly these contain non-critical information (i.e. your private keys etc)
If you'd like to create a separate file to isolate from the other config files, you could create a file f.ex. config/constants.php
and return an array as it is done in other config files. Make it a flat array (no 'CONST'
key). In the app/providers/AppServiceProvider
in the register()
method add
$this->mergeConfigFrom('config/constants.php', 'constants');
This way you can access your constants with config('constants.THE_ID_OF_SOMETHING_NICE');
Upvotes: 1