Laravel use findOrFail for configuration

Laravel use findOrFail for configuration

Posted on:August 20, 2024 at 02:15 PM

In laravel, you have a config/foo.php config file like this:

<?php

return [
    'foo' => env('FOO'),
];

Scenario 1:

If you somehow forget to set the value of FOO in the .env file for the production, your application may not act properly. In that case, since Laravel 10 you can use Env::getOrFail('FOO') in your configuration file.

For example:

<?php

use Illuminate\Support\Env;

return [
    'foo' => Env::getOrFail('FOO')
];

What are the benefits?

This method is used to retrieve an environment variable and will throw a RuntimeException if the variable is not found, ensuring that your application fails early if a required environment variable is missing.

Scenario 2:

Alternatively you can define the default value in the configuration like this:

<?php

return [
    'foo' => env('FOO', 'SOME-DEFAULT-VALUE'),
];

There is a problem though!

In that case, you are exposing your default value to other developers or anyone has access in the code repository! So, it’s suggested to use Scenario 1 which is much save with guard.

Thanks.