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.
<?php
return [
'url' => 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.