Cannot access env variables in Laravel

Viewed 6258

I'm have an issue in accessing the env variables from env file in Laravel. The application is already hosted to one of shared hosting sites. When I printed the APP_KEY variable, it returns empty.

I tried to check if the env file exists by using file_exists function inside the index.php file in the public directory and it returns true yet I cannot access the env variables. Thus, resulting to error in cipher because of empty appkey.

This happened after this code block in the index.php file in the public directory:

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

When I print the $response->send(), it showed the cipher error.

I did the same thing in my local and it displayed the appkey value with no cipher error.

The files I used in the shared hosting site are the same files from my local. This is the first time I host the Laravel application. Maybe there are some things I missed?

Do you have any idea why this happening? Thanks.

3 Answers

A possibility is that config caching is enabled. In that case, only env calls in the config/ dir return a value.

This is cryptically explained in the config docs https://laravel.com/docs/5.5/configuration

If you execute the config:cache command during your deployment process, you should be sure that you are only calling the env function from within your configuration files.

In Laravel 8 there have an issue, you cannot get the env variable direct assign env("URL")

To simplify:

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

URL="http://google.com"

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

config/getURL.php

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

<?php return ['url' => env('URL') ];

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

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

Step 5.) Now you can we env variable in the controller

public function url() {return config('example.url');}

Finally, Clear the cache:

PHP artisan config:cache

Related