Accessing Laravel .env variables in blade

I am trying to get some API keys which I have stored in my .env file to use in the blade javascript. I have added two keys like:

APP_ENV=local
APP_KEY=////
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost
APP_GOOGLE_MAPS=////
APP_OVERHEID_IO=////

In blade I need to use the Google Maps API and OverheidIO API key. I have tried getting one of the default .env variables just in case I have formatted the custom .env variables wrong.:

{{ env('APP.ENV') }} // nothing
{{ env('APP_ENV') }} // nothing
{{ env('APP_ENV'), 'test' }} // returns 'test' 

Could someone help me call the google maps api and overheidio api key in the blade?


Solution 1:

Five most important commands if your Laravel is not working as expected after some modifications in .env or database folder or because of any other modifications. Here is full explanation: https://www.youtube.com/watch?v=Q1ynDMC8UGg

php artisan config:clear
php artisan cache:clear
composer dump-autoload
php artisan view:clear
php artisan route:clear

Solution 2:

I have it implemented in the following way:

@if (env('APP_ENV')!='Production')
Enviroment Test
@endif

My recommendation is to execute the following command: composer self-update

Solution 3:

VERY IMPORTANT

All env() like: env('APP_ENV') calls WON'T WORK in production (when you use php artisan config:cache)

What to use?
- use env() only in config files
- use App::environment() for checking the environment (APP_ENV in .env).
- use config('app.var') for all other env variables, ex. config('app.debug')
- create own config files for your own ENV variables. Example:
In your .env:

MY_VALUE=foo

example config app/myconfig.php

return [
    'myvalue' => env('MY_VALUE', 'bar'), // 'bar' is default if MY_VALUE is missing in .env
];

Access in your code:

config('myconfig.myvalue') // will result in 'foo'

More details see HERE

Solution 4:

You should only access .env values directly inside configuration files, then access them from everywhere (controllers, views) from configuration files using config() helper

For example:

.env

TEST_URL=http://test

config/app.php

return [
   'test_url' => env('TEST_URL','http://default.url')
];

resources/views/welcome.blade.php

{{ config('app.test_url')}}

see configuration caching from laravel documentation for more info.

Solution 5:

If you want to get the environment of the app then try this:

{{App::environment()}}

I have not tried other variables.