Getting the following error when I access my Laravel app from the browser
A portion of the .env
file
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
I have tried running the following commands
php artisan config:clear
php artisan cache:clear
composer dump-autoload
Every command I run results in the same error
I have also tried deleting and creating a new .env
file.
2
Answers
The null coalescing operator (??) does not work the same on objects as it works on arrays. While this works fine if $settings does not have a "smtp_port" key
for objects you need to do something like this:
either way 2 things to keep in mind:
as a rule of thumb, only cast the resulting operation, rather than each part individually
ex:
(int)($settings?->smtp_port ?? env('MAIL_PORT'))
don’t use
env()
outside of config files since the environment variables will NOT be loaded if the config is cached.Understanding the issue
Output:
And now let’s consider this one:
Output:
So, we can say with certainty that:
$settings
isnull
$settings->smtp_host ?? 'abc'
does not error out despite the fact that$settings
isnull
and, instead falls back to abc(int)$settings->smtp_host ?? 'abc'
errors out because in order to evaluate(int)$settings->smtp_host
the evaluation of$settings->smtp_host
is a necessity and since$settings
isnull
, it errors out despite the fact that you have a??
, because you basically force the reaching of a field of anull
variableTechnical solution for such evaluations
If
$settings
isnull
, that means it was uninitialized and you need to initialize it and then you will need to ensure the fields:Now, let’s build your array:
and you can assign
$someArray
as the value of your'smtp'
field.