Loading GOOGLE_APPLICATION_CREDENTIALS in Laravel 5 - php

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() to config()), 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!

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',
]);

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

Related

PHP fails to access the docker socket via curl

My Code fails to reach the Docker Socket
$client = new GuzzleHttp\Client();
$test = $client->request('GET','http://v1.40/containers/json',[
'curl' => [CURLOPT_UNIX_SOCKET_PATH => '/var/run/docker.sock']
]);
I only get a generic cURL error 7 from that and I´ve checked that the socket is available and working inside the Container with the cURL command from the cmd. Its only when i try to connect via PHP it fails ominously and frankly im out of ideas.
So just in case someone stumbles upon this in the future and has the same or a similar problem.
Guzzle was not the problem in this case but phpfpm. I did not realize that the phpfpm workers in the official php docker image used the www-data user by default. The way I used is to change the user in the www.conf (default /usr/local/etc/php-fpm.d/www.conf in docker)
user = root
group = root
you will have to append the -R flag to the run command to allow running the workers as root.

NGINX Caching Symlinked Web Site Location

I have this weird issue that was not happening before.
I am running a Ubuntu Box on Digital Ocean that uses NGINX and PHP-FPM. I also use PHP Deployer to deploy code between Stage and Prod.
Deployer uses symlinks to tell the server where the files are in this case /var/www/mydommain.com/current would be the symlink that points to /var/www/mydomain.com/releases/26.
That is all good and if I do cd /var/www/mydomain.com/current it will change to releases/26. The website however is still pointing to releases/25. I have restarted NGINX and PHP-FPM multiple time without success.
Why is NGINX still pointing to releases/25 when the symlink actually points to releases/26? I can't get it.
In NGINX config for this domain I have root /var/www/mydomain.com/current
I know this is an 8 months old question, but this might help others:
I ran into the same issue and noticed that if I edit my index file (index.php) of the previous release, the symlink is magically refreshed.
After deploying, I simply run:
touch /path/to/releases/[previous_release_number]/public_html/index.php
...to update the file's modification timestamp.
I ended up including it in my deploy:symlink task like this:
task('deploy:symlink', function () {
run("cd {{deploy_path}} && ln -sfn {{release_path}}/public_html ./public_html");
run("touch {{previous_release}}/public_html/index.php");
})->desc('Linking latest version to public_html'); // <= Added this
Hope this helps.
Regards, Wouter
This can be due to $document_root in your Nginx configuration being cached until you do sudo service php5.6-fpm restart.
You can replace $document_root with $realpath_root to avoid the caching.
This website helped me:
https://joshtronic.com/2019/07/29/symlinks-with-nginx-and-php-fpm/

Laravel looking for path on my localhost instead of deployed server

I have Laravel installed on my localhost. And when I try to deploy it to the server, it throws an error: View [frontend.layouts.login] not found.
And I can see that it is looking at my local file path when on my machine aka:
/Applications/MAMP/htdocs/personal/project_name/resources/views
Instead of the server's file path.
If I try and copy the project outside of the personal folder (on my local machine), so make the file path:
/Applications/MAMP/htdocs/project_name/resources/views
It gives the same issue?
Is it something with caching the views?
The other error on the same page is:
file_put_contents(/Applications/MAMP/htdocs/personal/project_name/storage/framework/sessions/7a0aaa6c977031111312b785c7b7e22a659b6a36): failed to open stream: No such file or directory
And again, the server has nothing to do with my local machine.
What could be going on?
This issue is due to the Laravel Configuration Caching.I suggest you
Remove the configuration cache file
Flush the application cache
Create a cache file for faster configuration loading
To do this, run the following Artisan commands on your command line
php artisan config:clear
php artisan cache:clear
php artisan config:cache
Where you don't have access to the command line on your server, you can programmatically execute commands like this:
Route::get('/clear-cache', function() {
$exitCode = Artisan::call('config:clear');
$exitCode = Artisan::call('cache:clear');
$exitCode = Artisan::call('config:cache');
return 'DONE'; //Return anything
});
I hope this is helpful.
I think this might fix it
Go to config/app.php
and change the url to your production url
'url' => 'http://localhost',
I had the same issue so i tried many things including all the solutions in this question, but it didn't work.
What worked for me is that i just deleted this file bootstrap/cache/config.php and it worked.

Laravel 5.2 not reading env file

After upgrading to Laravel 5.2, none of my .env file values are being read. I followed the upgrade instructions; none of my config files were changed except auth.php. They were all working fine in previous version, 5.1.19
.env contains values such as
DB_DATABASE=mydb
DB_USERNAME=myuser
config/database.php contains
'mysql' => [
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
]
I get this error:
PDOException: SQLSTATE[HY000] [1045] Access denied for user 'forge'#'localhost' (using password: NO)
Clearly not pulling in my env config. This is affecting every single one of my config files, including third party such as bugsnag.
I also tried
php artisan config:clear
php artisan cache:clear
Update
Trying php artisan tinker
>>> env('DB_DATABASE')
=> null
>>> getenv('DB_DATABASE')
=> false
>>> config('database.connections.mysql.database')
=> "forge"
>>> dd($_ENV)
[]
I have tried installing a fresh copy of Laravel 5.2. I basically only copied in my app folder; no additional composer packages are included. Still having the same issue. I have other Laravel 5.2 projects on the same server that are working fine.
If any of your .env variables contains white space, make sure you wrap them in double-quotes. For example:
SITE_NAME="My website"
Don't forget to clear your cache before testing:
php artisan config:cache
php artisan config:clear
From the official Laravel 5.2 Upgrade Notes:
If you are using the config:cache command during deployment, you
must make sure that you are only calling the env function from within
your configuration files, and not from anywhere else in your
application.
If you are calling env from within your application, it is strongly
recommended you add proper configuration values to your configuration
files and call env from that location instead, allowing you to convert
your env calls to config calls.
Reference: https://laravel.com/docs/5.2/upgrade#upgrade-5.2.0
For me it has worked this in this order:
php artisan config:cache
php artisan config:clear
php artisan cache:clear
And I've tried all the rests without luck.
Wow. Good grief. It's because I had an env value with a space in it, not surrounded by quotes
This
SITE_NAME=My website
Changed to this
SITE_NAME="My website"
Fixed it. I think this had to do with Laravel 5.2 now upgrading vlucas/phpdotenv from 1.1.1 to 2.1.0
I had a similar issue in my config/services.php and I solved using config clear and optimize commands:
php artisan config:clear
php artisan optimize
You can solve the problem by the following recommendation
Recommendation 1:
You have to use the .env file through configuration files, that means you are requrested to read the .env file from configuration files (such as /config/app.php or /config/database.php), then you can use the configuration files from any location of your project.
Recommendation 2: Set your env value within double quotation
GOOGLE_CLIENT_ID="887557629-9h6n4ne.apps.googleusercontent.com"
GOOGLE_CLIENT_SECRET="YT2ev2SpJt_Pa3dit60iFJ"
GOOGLE_MAP="AIzaSyCK6RWwql0DucT7Sl43w9ma-k8qU"
Recommendation 3: Maintain the following command sequence after changing any configuration or env value.
composer dump-autoload
composer dump-autoload -o
php artisan clear-compiled
php artisan optimize
php artisan route:clear
php artisan view:clear
php artisan cache:clear
php artisan config:cache
php artisan config:clear
Recommendation 4: When the syntax1 is not working then you can try another syntax2
$val1 = env('VARIABLE_NAME'); // syntax1
$val2 = getenv('VARIABLE_NAME'); // syntax2
echo 'systax1 value is:'.$val1.' & systax2 value is:'.$val2;
Recommendation 5: When your number of users is high/more then you have to increase the related memory size in the server configuration.
Recommendation 6: Set a default probable value when you are reading .env variable.
$googleClinetId=env("GOOGLE_CLIENT_ID","889159-9h6n95f1e.apps.googleusercontent.com");
$googleSecretId=env("GOOGLE_CLIENT_ID","YT2evBCt_Pa3dit60iFJ");
$googleMap=env("GOOGLE_MAP","AIzaSyCK6RUl0T7Sl43w9ma-k8qU");
I missed this in the upgrade instructions:
Add an env configuration option to your app.php configuration file that looks like the following:
'env' => env('APP_ENV', 'production')
Adding this line got the local .env file to be read in correctly.
I had the same issue on local environment, I resolved by
php artisan config:clear
php artisan config:cache
and then cancelling php artisan serve command, and restart again.
Same thing happens when :port is in your local .env
again the double quotes does the trick
APP_URL="http://localhost:8000"
and then
php artisan config:clear
Also additional to what #andrewtweber suggested make sure that you don't have spaces between the KEY= and the value unless it is between quotes
.env file e.g.:
...
SITE_NAME= My website
MAIL_PORT= 587
MAIL_FROM_NAME= websitename
...
to:
...
SITE_NAME="My website"
MAIL_PORT=587
MAIL_FROM_NAME=websitename
...
I solved this problem generating a new key using the command: php artisan key:generate
if you did call config:cache during local development, you can undo this by deleting the bootstrap/cache/config.php file. and this is work for me.
In my case laravel 5.7 env('APP_URL') not work but config('app.url') works. If I add new variable to env and to config - it not works - but after php artisan config:cache it start works.
if you did call config:cache during local development, you can undo this by deleting the bootstrap/cache/config.php file. and this is work for me.
#Payal Pandav has given the comment above.
I want to tell a simple workaround. Just edit the config.php file in the bootstrap/cache/ folder. And change the credentials. This worked for me. Please don't delete this file since this may contain other crucial data in the production environment.
I experienced this. Reason was that apache(user www-data) could not read .env due to file permissions.
So i changed the file permissions to ensure that the server (apache) had read permissions to the file. Just that and boom, it was all working now!
Update:How to do this varies, depending on who owns the .env file, but assuming it belongs to the Apache www-data group, you can do this:
sudo chmod g+r .env
Modify it depending on your permission structure.
In my case, I needed to restart my Supervisord jobs (i.e. my queue workers). After doing so, a new environment variable I had added to my .env file was successfully pulled into my application.
Remember, queue workers, are long-lived processes and store the booted application state in memory. As a result, they will not notice changes in your code base after they have been started. So, during your deployment process, be sure to restart your queue workers. In addition, remember that any static state created or modified by your application will not be automatically reset between jobs.
Source: Official Laravel Docs - Queues
I know this is super old, but today I discovered another reason why my .env was not loaded:
I had a (commited) .env.local
I recently switched APP_ENV from dev to local
With L8 (and maybe before), what happens is that it tries to find .env.<APP_ENV> and if it finds it, uses it.
Fun fact: in my case, .env.local was a blue-print file with non-sensitive information and not meant to be directly used, but that's what happened.
Removing the .env.local led to Laravel looking for .env instead.
In my case I was using VSCODE and it turned out my .env file was auto-dectected by the IDE as a shell script file and not an Ini which was causing me the issue. It's a rare occurrence, but I hope it will save someone time.
For Laravel coder. We can use config() to solve this problem
in file "config/app.php":
'same_url' => env('SAME_URL', 'http://localhost'),
in your code base:
$sameURL = config('app.same_url').'/orders/';
If you've come here because you have multiple .env.* files and php artisan config:cache resulted in incorrect settings, it's because it (tried to) read the .env file and not the one specific to your environment. Try this instead (where CODE corresponds to .env.CODE):
APP_ENV=CODE php artisan config:cache
I made the mistake by doing dd/die/dump in the index.php file. This causes the system to not regenerate the configs.
Just do dump in view files will do. The changes to .env file update instantly.
I had some problems with this.
It seemed to be a file permission issue somewhere in the app - not the .env-file.
I had to
- stop my docker
- use chown to set owning-rights to my own user for the whole project
- start docker again
This time it worked.
If you're using sail environment right after you change your environment variable just restart a server, otherwise it's going to show the old value.
In my case (Laravel 7.x) it happen because I had set environmental variable on server. To be precise in Docker container.
And because environments variables are higher priority than .env file, nothing changes during .env file edit.
Check if you set the env variable on the server:
echo $VAR_NAME
Tried almost all of the above. Ended up doing
chmod 666 .env
which worked. This problem seems to keep cropping up on the app I inherited however, this most recent time was after adding a .env.testing. Running Laravel 5.8

Laravel view not found exception

I have problem with laravel view is not found by route function I did composer dumpautoload but no use
ArticleController.php
<?php
class ArticleController extends BaseController
{
public function showIndex()
{
return View::make('index');
}
public function showSingle($articleId)
{
return View::make('single');
}
}
//Route
Route::get('index', 'ArticleController#showIndex');
InvalidArgumentException
View [index] not found.
open: /opt/lampp/htdocs/laravel-project/bootstrap/compiled.php
foreach ((array) $paths as $path) {
foreach ($this->getPossibleViewFiles($name) as $file) {
if ($this->files->exists($viewPath = $path . '/' . $file)) {
return $viewPath;
}
}
}
throw new \InvalidArgumentException("View [{$name}] not found.");
}
protected function getPossibleViewFiles($name)
Server/Request Data
REDIRECT_UNIQUE_ID UfWlAn8AAQEAABR2VakAAAAF
REDIRECT_STATUS 200
UNIQUE_ID UfWlAn8AAQEAABR2VakAAAAF
HTTP_HOST localhost
HTTP_USER_AGENT Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0
HTTP_ACCEPT text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
HTTP_ACCEPT_LANGUAGE en-US,en;q=0.5
HTTP_ACCEPT_ENCODING gzip, deflate
HTTP_COOKIE laravel_session=f94fpel78jn89nhah32mflqn15
HTTP_CONNECTION keep-alive
HTTP_CACHE_CONTROL max-age=0
PATH /usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
LD_LIBRARY_PATH /opt/lampp/lib:/opt/lampp/lib
SERVER_SIGNATURE
SERVER_SOFTWARE Apache/2.4.4 (Unix) OpenSSL/1.0.1e PHP/5.4.16 mod_perl/2.0.8-dev Perl/v5.16.3
SERVER_NAME localhost
SERVER_ADDR 127.0.0.1
SERVER_PORT 80
REMOTE_ADDR 127.0.0.1
DOCUMENT_ROOT /opt/lampp/htdocs
REQUEST_SCHEME http
CONTEXT_PREFIX
CONTEXT_DOCUMENT_ROOT /opt/lampp/htdocs
SERVER_ADMIN you#example.com
SCRIPT_FILENAME /opt/lampp/htdocs/laravel-project/public/index.php
REMOTE_PORT 50211
REDIRECT_URL /laravel-project/public/index
GATEWAY_INTERFACE CGI/1.1
SERVER_PROTOCOL HTTP/1.1
REQUEST_METHOD GET
QUERY_STRING
REQUEST_URI /laravel-project/public/index
SCRIPT_NAME /laravel-project/public/index.php
PHP_SELF /laravel-project/public/index.php
REQUEST_TIME_FLOAT 1375053058.123
REQUEST_TIME 1375053058
This error also occurs when you try to move the whole project directory to other path. And you happened to run the following commands below BEFORE you move.
php artisan optimize --force
php artisan config:cache
php artisan route:cache
Mine error message shows like this
As you can see the old path was written in the compiled.php. So, to fix the problem. Simply run the same command AGAIN under the project folder in your new folder location.
php artisan optimize --force
php artisan config:cache
php artisan route:cache
Hope this helps.
This happens when Laravel doesn't find a view file in your application. Make sure you have a file named: index.php or index.blade.php under your app/views directory.
Note that Laravel will do the following when calling View::make:
For View::make('index') Laravel will look for the file: app/views/index.php.
For View::make('index.foo') Laravel will look for the file: app/views/index/foo.php.
The file can have any of those two extensions: .php or .blade.php.
This command works for me
php artisan config:cache
As Laravel doc says that by default, Laravel is configured to use the file cache driver, which stores the serialized, cached objects in the filesystem. So it needs to recache the file system so that newly added views and route are available to show. I also not sure why laravel needs to recache actually
This might be possible that your view is present even though it shows the error. So to solve this issue you need to stop the server and run this command on the terminal.
php artisan config:cache
then restart the server
In my case I had to run php artisan optimize:clear in order to make everything to work again.
Somewhat embarrassingly, I discovered another rather trivial cause for this error: I had a full stop in the filename of my blade file (eg resources/views/pages/user.invitation.blade.php). It really did make sense at the time!
I was trying to reference it like so: view('pages.user.invitation')
but of course Laravel was looking for the file at resources/views/pages/user/invitation.blade.php and throwing the view not found.
Hope this helps someone.
Just in the controller call
return View('index');
without
::make
As #deanchiu said it may happen when you move the whole project to another path or server.
But in my case I had no access to command line on server and running following commands BEFORE I upload my project helped me.
> php artisan route:clear
> php artisan config:clear
In my case I was calling View::make('User/index'), where in fact my view was in user directory and it was called index.blade.php. Ergo after I changed it to View#make('user.index') all started working.
I was having the same error, but in my case the view was called seeProposal.
I changed it to seeproposal and it worked fine...
It was not being an issue while testing locally, but apparently Laravel makes a distinction with capital letters running in production. So for those who have views with capital letters, I would change all of them to lowercase.
check your blade syntax on the view that said not found
i just fix mine
#if
#component
#endif
#endcomponent
to
#if
#component
#endcomponent
#endif
Use this on your cmd then run your project.
php artisan config:cache php artisan route:cache php artisan
controller:cache php artisan optimize:clear
If your path to view is true first try to config:cache and route:cache if nothing changed check your resource path permission are true.
example: your can do it in ubuntu with :
sudo chgrp -R www-data resources/views
sudo usermod -a -G www-data $USER
In addition to these answers, if your view is in an unusual directory for the project, you'll have to add the following to /config/view.php
'paths' => [
resource_path('views'),
resource_path('../path/from/project/route/to/view')
],
If you are not accessing files as root user you shall change access of files
Change Access group to Access files
Also, others to Access files
it's work for me
If you are using GIT in your project don't forget make git add . and commit before of move the project to another side and also don't forget clean the cache.
In my case, Laravel 5.3
Route::get('/', function(){
return View('test');
});
test.blade.php was not rendering but some other views were rendering on localhost via XAMPP on mac. Upon running artisan server, the view started rendering for same url over XAMPP.
php artisan serve
To avoid any such scenario, one should test the Laravel apps with artisan server only.
Create the index.blade.php file in the views folder, that should be all
I had the same error. I created a directory under views direcotry named users and created an index.blade.php file in it. When calling this file you should write users.index to indicate your path. Or just create index.blade.php file under views. hope this will help someone who gets the same problem

Categories