Why PHP Artisan Tinker kept showing null? - php

┌──[root#jdoe]──[/home/jdoe/jdoe]
└── cat .env | grep APP_URL
APP_URL=https://www.jdoe.com
┌──[root#jdoe]──[/home/jdoe/jdoe]
└── php artisan tinker
Psy Shell v0.10.2 (PHP 7.3.11-0ubuntu0.19.10.3 — cli) by Justin Hileman
>>> env('APP_URL')
=> null
>>> env('APP_URL');
=> null
>>>
I support to see https://www.jdoe.com
Someone want to explain this ?

Try restart Tinker. Sometimes it saves state somehow, so I get used to restart if I change something somewhere
Try php artisan optimize:clear. I think that should resolve your problem because Laravel defenetly store some state in cache if you set some settings

Related

Why does php artisan tinker redirect to my project directory?

I'm following this tutorial: https://www.youtube.com/watch?v=neSHAWdE44c&index=5&list=PLillGF-RfqbYhQsN5WMXy6VsDMKGadrJ-
At time 7:17, he uses php artisan tinker.
No matter what I do and/or try, upon running php artisan tinker, I then run App\Post::count() but all it does is redirect me back to the project directory.
I can't even do a simple 2 + 2 and see the output. I just get redirected back to the project directory.
I'm using Laravel 5.7.25 if that's of any help.
I've looked all over SO but I'm trying to hang in there in terms of finding a solution. Anybody have an idea what's causing this?
Example of what I mean:
name-MBP:lsapp name$ php artisan tinker
Psy Shell v0.9.9 (PHP 7.3.1 — cli) by Justin Hileman
>>> App\Post::count()
name-MBP:lsapp name$
It is an issue with Psy Shell
Try creating a file named config.php at ~/.config/psysh or C:\Users\{USER}\AppData\Roaming\PsySH (for windows) if not already there.
and put this as the content:
<?php
return [
'usePcntl' => false,
];

env values from Linux not loaded by Laravel config app

Some time ago I asked about setting env settings and how to properly use them. I was quickly pointed to a comparable question and I found out that indeed it was bad practice to use env('KEY') throughout your code.
So now I am in the process of migrating my env settings to config/app.php.
However, if I play with Tinker, the env variables from Linux are not loaded by Laravel. For instance, if I place:
'test' => 'testing123',
within the config/app.php
and do a
sudo php artisan config:cache
and employ Tinker
config('app.test');
=> "testing123"
So that seems to work. However, if I place the following
'test' => env('DB_PORT'),
and do a
sudo php artisan config:cache
and test this with tinker:
config('app.test');
=> null
But when I am in the console and use:
env|grep DB_PORT
I see the right value for the DB_PORT key. I am supplying these in AWS frontend, these properties are then passed in the application as environment properties.
Anyone any idea why these are not imported/loaded correctly?
php artisan config:clear
Or you can just manually delete bootstrap/config.php, which is what artisan does after all.
See: vendor\laravel\framework\src\Illuminate\Foundation\Console\ConfigClearCommand.php

Laravel .env constants not working with mail.php

The error:
In my mail.php file, if I set
'driver' => env('MAIL_DRIVER'),
and have this to my .env file:
MAIL_DRIVER=log
Then I get the following error:
Swift_TransportException in AbstractSmtpTransport.php line 383:
Expected response code 250 but got code "530",
with message "530 5.7.1 Authentication required"
The wonky work-around
In my mail.php file, I have the following:
'driver' => 'log',
works fine.
The Conclusion
My theory is that mail.php is not reading my .env file constant correctly, since replacing it with the actual string fixes the problem. However, the defaults for this file all make use of .env constants, so I'm wondering why are my .env constants not getting recognized in my mail.php file?
FYI
In other files besides mail.php in the same app, I am using other .env constants that work just fine. For instance, in my UserTableSeeder class, I have:
factory(App\User::class, 1)->create([
'email' => env('ADMIN_EMAIL'),
'password' => Hash::make(env('ADMIN_PASSWORD')),
'is_admin' => 1
]);
which successfully makes use of the below constants from my .env file:
ADMIN_EMAIL=xxxxxxx#yahoo.com
ADMIN_PASSWORD=xxxxxxx
I tried the below 2 php artisan commands (php artisan cache:clear and php artisan config:clear), but "smtp" continued to output when "log" is what I have in my .env file:
04:52:54 Fri May 13 vagrant#homestead (email_notifications) [130]
~/Code/myapp $ php artisan config:clear
Configuration cache cleared!
05:52:56 Fri May 13 vagrant#homestead (email_notifications) [0]
~/Code/myapp $ php artisan tinker
Psy Shell v0.6.1 (PHP 7.0.2-4+deb.sury.org~trusty+1 — cli) by Justin Hileman
>>> dd(env('MAIL_DRIVER'));
"smtp"
>>> exit
Exit: Goodbye.
05:53:23 Fri May 13 vagrant#homestead (email_notifications) [0]
~/Code/myapp $ php artisan cache:clear
Application cache cleared!
05:53:48 Fri May 13 vagrant#homestead (email_notifications) [0]
~/Code/myapp $ php artisan tinker
Psy Shell v0.6.1 (PHP 7.0.2-4+deb.sury.org~trusty+1 — cli) by Justin Hileman
>>> dd(env('MAIL_DRIVER'));
"smtp"
I am not sure whether you have solved it or not yet. But I'll try to provide a way too simple solution.
Short Answer: You need to immediately reboot the application as and when you make changes in your .env file.
Not So Long Answer: It is happening because your .env file is already being accessed by the laravel application. If you make changes in your .env file while your application is running in your local machine, it will not recognize it instantly. You will have to shut down your entire laravel application and reboot it once using $ php artisan serve.
Doing so, it will definitely take up the environment constants and you will get the desired result.
Hope this helps you out. Happy coding. Cheers.
There might be default constants in the .env file that includes one for MAIL_DRIVER=sftp. If you add additional values for the same constant, the FIRST constant is the one that will get defined. Thus, make sure to have just 1 constant definition in your .env file, or at least have it be the 1st one if for some reason you want more than one constant in there.

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

Lumen Micro Framework => php artisan key:generate

I'm trying out the PHP micro Framework Lumen (from Laravel).
One of my first steps was to look into the .env.example file and make a copy of it to have my .env file. There is a variable APP_KEY just like there is in Laravel. Now I tried out the simple command php artisan key:generate to get my new key But I ran into the following error message:
[InvalidArgumentException] There are no commands defined in the "key"
namespace.
Does some one know how I can generate keys for Lumen?
Update with solution
So I found my favorite solution for this problem. On the command line (Linux) I run php -r "echo md5(uniqid()).\"\n\";" what gives me something like this 7142720170cef01171fd4af26ef17c93.
If you are going to use Lumen more often, you may want to create an alias in your .bashrc, which is located in your home directory /home/USERNAME. To do so, you can open the file with nano ~/.bashrc or vi ~/.bashrc and copy the following alias at the end of the file, alias phpkey='php -r "echo md5(uniqid()).\"\n\";"'. Now you can use the command phpkey which will give you a 32 character long random string :)
The Laravel command is fairly simple. It just generates a random 32 character long string. You can do the same in Lumen. Just temporarily add a route like this:
$router->get('/key', function() {
return \Illuminate\Support\Str::random(32);
});
Then go to /key in your browser and copy paste the key into your .env file.
Afterwards remove the route.
Obviously you could also use some random string generator online. Like this one
Firstly, you have to register your key generator command, put this Lumen Key Generator Commands to app/Console/Commands/KeyGenerateCommand.php. To make this command available in artisan, change app\Console\Kernel.php:
/**
* The Artisan commands provided by your application.
*
* #var array
*/
protected $commands = [
'App\Console\Commands\KeyGenerateCommand',
];
After that, configure your application so that Illuminate\Config\Repository instance has app.key value. To do this, change bootstrap/app.php:
<?php
require_once __DIR__.'/../vendor/autoload.php';
Dotenv::load(__DIR__.'/../');
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| Here we will load the environment and create the application instance
| that serves as the central piece of this framework. We'll use this
| application as an "IoC" container and router for this framework.
|
*/
$app = new Laravel\Lumen\Application(
realpath(__DIR__.'/../')
);
$app->configure('app');
After that, copy your .env.example file to .env:
cp .env.example .env
Ignore this step if you already use .env file.
Enjoy you key:generate command via:
php artisan key:generate
Edit
You may use Lumen Generator. It covers so much commands you are missing from Laravel.
Simply use PHP CLI. Run this from your local or a remote command line to generate a random 32-character Lumen APP_KEY:
php -r "echo bin2hex(random_bytes(16));"
Output: bae48aba23b3e4395b7f1b484dd25192
Works with PHP 7.x on Mac and Windows.
An easy solution is just running PHP code from the terminal (without using tinker, because that is not available with Lumen):
php -r "require 'vendor/autoload.php'; echo str_random(32).PHP_EOL;"
It uses Laravel's Str::random() function that makes use of the secure random_bytes() function.
For me the easiest way to generate a Lumen key is typing on console one of these commands:
date | md5
date | md5sum
or
openssl rand -base64 24
depending of your environment. In my case, I aways use date | md5 on mac
The APP_KEY generation is a step of development process (I don't think that creating temporarily routes is a practical way to do it). The function str_random can help us, but this function is part of Laravel/Lunmen framework.
I recommend running tinker
php artisan tinker
and then run the function
>>> str_random(32)
The result is the key you're looking for.
=> "y3DLxnEczGWGN4CKUdk1S5GbMumU2dfH"
To generate key and use laravel command you need to install one package. The details are as below:
You have to install package composer require flipbox/lumen-generator
You have to add $app->register(Flipbox\LumenGenerator\LumenGeneratorServiceProvider::class); into bootstrap/app.php file.
Link: https://github.com/flipboxstudio/lumen-generator
All I do on mac is execute this command in the terminal:
date | md5 | pbcopy
This copies the value into the clipboard and so you can easily paste the key into the .env file.
I have used these commands:
php -r \"copy('.env.example', '.env');\"
php -r "echo password_hash(uniqid(), PASSWORD_BCRYPT).\"\n\";"
The command generates a key similar to this:
$2y$10$jb3kw/vUANyzZ4ncMa4rwuR09qldQ2OjX8PGrVB5dIlSnUAPCGjFe
This answer was inspired by #thomas-venturini 's update to the question. Here's a bash script that takes care of creating .env and updating it with an APP_KEY using the aforementioned PHP command and the UNIX sed command:
#!/usr/bin/env bash
function generate_app_key {
php -r "echo md5(uniqid()).\"\n\";"
}
APP_KEY=$(generate_app_key)
sed -e s/APP_KEY=.*$/APP_KEY=${APP_KEY}/g .env.example > .env
Hope someone finds this useful.
Run php -a to start up interactive php playground.
Then run echo substr(md5(rand()), 0, 32); to generate a 32 character string.
You can then copy/paste into the .env file.
1.Open your terminal setup file:
vim ~/.zshrc
2.Create an alias for generating random strings:
# Lumen Key Generate
alias lumen-key="php -r \"require 'vendor/autoload.php'; echo base64_encode(str_random(32)).PHP_EOL;\""
3.Get a key whenever you need:
~/your-lumen-project via 🐘 v7.3.0
➜ lumen-key
VkxTYWZZSnhVNVEzRThXelBGZVJDVGZVYTNTcm9peHY=
You can also remove the third step by adding the key directly in .env using PHP.
[Flipbox\LumenGenerator]
Fix error: there are no comands defined...
[boostrap/app] Check if you register the Flipbox\LumenGenerator after return $app. If so move the Service provider register before return app...
/**
* Configure extra LARAVEL commands to a lumen app
* Check avaliable commands in git: flipboxstudio lumen-generator
*/
if($app->environment() !== 'production'){
$app->register(Flipbox\LumenGenerator\LumenGeneratorServiceProvider::class);
}
return $app;
Lumen 8.0 / flipbox/lumen-generator 8.2
It Worked 100%
Simply install the flipbox/lumen-generator package
composer require flipbox/lumen-generator.
Inside your bootstrap/app.php file, add:
$app->register(Flipbox\LumenGenerator\LumenGeneratorServiceProvider::class);
Then after you can able to run php artisan commands,
more info: https://github.com/flipboxstudio/lumen-generator

Categories