Get environment value in controller

前端 未结 10 1660
既然无缘
既然无缘 2020-12-25 10:43

In my .env file I have the following:

IMAP_HOSTNAME_TEST=imap.gmail.com
IMAP_USERNAME_TEST=myemail@gmail.com
IMAP_PASSWORD_TEST=mypw

Now I

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-25 11:02

    To simplify: Only configuration files can access environment variables - and then pass them on.

    Step 1.) Add your variable to your .env file, for example,

    EXAMPLE_URL="http://google.com"
    

    Step 2.) Create a new file inside of the config folder, with any name, for example,

    config/example.php
    

    Step 3.) Inside of this new file, I add an array being returned, containing that environment variable.

     env('EXAMPLE_URL')
    ];
    

    Step 4.) Because I named it "example", my configuration 'namespace' is now example. So now, in my controller I can access this variable with:

    $url = \config('example.url');
    

    Tip - if you add use Config; at the top of your controller, you don't need the backslash (which designates the root namespace). For example,

    namespace App\Http\Controllers;
    use Config; // Added this line
    
    class ExampleController extends Controller
    {
        public function url() {
            return config('example.url');
        }
    }
    

    Finally, commit the changes:

    php artisan config:cache
    

    --- IMPORTANT --- Remember to enter php artisan config:cache into the console once you have created your example.php file. Configuration files and variables are cached, so if you make changes you need to flush that cache - the same applies to the .env file being changed / added to.

提交回复
热议问题