'Loading GOOGLE_APPLICATION_CREDENTIALS in Laravel 5
I'm using Laravel 5.2 and I do php artisan config:cache as recommended in the official documentation for speed improvement.
As you may know, this command makes the .env file variables directly inaccessibles (you can test it with php artisan tinker), and for that reason all the calls to env() and getenv() function must be replaced by config() in the code, except for the files in the config folder. After executing this command, calls like env('APP_ENV') return NULL.
In my project, I'm connecting to Google Cloud using the google-auth-library-php. Unfortunately, in the CredentialsLoader.php file there is a call to the function getenv(self::ENV_VAR) that attempts to get the path of the Google credentials file. As I run the command php artisan config:cache, the path can't be read from the .env file and the connection cannot be completed.
I can see 3 ways to continue:
- Forget about running
php artisan config:cache. - Ask here if somebody knows how to specify the path of the Google credentials file as a parameter of any function of the package.
- (Forgive me, God) Correct the CredentialsLoader.php file (
getenv()toconfig()), run the command and track this file in the repository, then this change will propagate to every team member when they pull.
Thank you in advance!
Solution 1:[1]
That's a very old question but maybe it can be useful for someone coming for the same problem even in the newer versions of Laravel.
Basically I don't have a solution that works for all the possible environments, but it gives the idea.
My environment runs php7.4-fpm with NGINX.
If you are using the same environment, you will have a location directives for your php files.
Nginx can set FastCGI parameters with fastcgi_param and you will have probably used it with SCRIPT_FILENAME etc..
You can can then add
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
[...]
fastcgi_param GOOGLE_APPLICATION_CREDENTIALS "/absolute/path/to/keyfile.json";
}
Then just reload Nginx (ex. for Ubuntu 20.04, sudo systemctl reload nginx).
For Apache the same idea would probably work with SetEnv https://httpd.apache.org/docs/2.4/mod/mod_env.html#setenv
Solution 2:[2]
For those who still encounter this error, you can specify the file using keyFile index in the first parameter:
$storage = new StorageClient([
'keyFile' => json_decode(file_get_contents($path), true),
]);
Or you can specify the .json file directly to config using keyFilePath index
$storage = new StorageClient([
'keyFilePath' => '/path/to/json/CompanyDataStorage-foobarbaz.json',
]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lorenzo S |
| Solution 2 |
