tuscan88
tuscan88

Reputation: 5829

Adding a new config file in Laravel 5 not working

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 protected]',
    'ADMIN_EMAIL' => '[email protected]'
];

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?

Upvotes: 15

Views: 19784

Answers (3)

Jinsong Li
Jinsong Li

Reputation: 7388

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

Upvotes: 1

lukasgeiter
lukasgeiter

Reputation: 152860

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');

Upvotes: 15

Bernig
Bernig

Reputation: 462

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 ;)

Upvotes: 29

Related Questions