15

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?

3 Answers 3

29

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

Sign up to request clarification or add additional context in comments.

Comments

15

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.