I want a new config file in my Laravel 5 app to store all my constants in. After looking around the net I found the recommended solution seems to be to create a new config file that returns an array of key value pairs and then use that. So I created the following file:
<?php
// config/constants.php
return [
'SITE_NAME' => 'Site Name',
'SITE_EMAIL' => 'email@site.com',
'ADMIN_EMAIL' => 'admin@site.com'
];
Then in one of my controllers I try to access one of these values like so:
echo Config::get('constants.ADMIN_EMAIL');
I just get the following error:
FatalErrorException in WelcomeController.php line 46:
Class 'App\Http\Controllers\Config' not found
Do I have to do something else to get it to work?
In Laravel 5, to avoid this kind of headache, you can use the config
helper function to get a config item, like this :
config('constants.ADMIN_EMAIL')
Nice and easy ;)
The Config
class is an alias in the global namespace. To reference it from inside the controller (which is in the App\\Http\\Controllers
namespace) you have to prepend it with a backslash:
echo \Config::get('constants.ADMIN_EMAIL');
Or add a use
statement above the controller class:
use Config;
class MyController extends Controller {
As an alternative you might also want to use dependency injection to access the config. That would look somewhat like this:
class MyController extends Controller {
public function __construct(Illuminate\Config\Repository $config){
$this->config = $config;
}
public function index(){
echo $this->config->get('constants.ADMIN_EMAIL');
}
}
As @Bernig suggests you can also simply use the new config()
helper function:
echo config('constants.ADMIN_EMAIL');
I met the same issue today, and I find an elegant solution: add the config/your_new_config.php
to ConfigServiceProvider
, like this:
/**
* Overwrite any vendor / package configuration.
*
* This service provider is intended to provide a convenient location for you
* to overwrite any "vendor" or package configuration that you may want to
* modify before the application handles the incoming request / command.
*
* @return void
*/
public function register()
{
config([
'config/your_new_config.php', // add your new config file here!
]);
}
The reason is well explained in the function's comments
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.