logo
podcast Podcast
get help Get Unstuck

Another way to get config values

With added type safety

Joel Clermont
Joel Clermont
2024-12-17

Laravel 11 introduced some new methods on the Config facade that lets you retrieve a configuration value with type safety.

use Illuminate\Support\Facades\Config;

// old way: everything fetched this way is `mixed`
Config::get('some-string-value');
Config::get('some-integer-value');

// new way: these return the actual type of the method
Config::string('some-string-value');
Config::integer('some-integer-value');

In addition to string and integer, there are methods for boolean, float, and array.

Why does this matter? Well, if your project is using PHPStan at higher levels, you may have to add @var docblocks to your code to get the static analysis to pass.

Personally, I view those docblocks as a last resort, so any time there's a different way, I like to use it.

This won't get rid of all need for config-related @var docblocks, however. For example, maybe you want to specify that the config value is an array of integers. That will still require a docblock. But in a recent project, these new helpers eliminated quite a few docblocks.

There's another nice lesson here: Keep up with new things that Laravel provides, and see when it makes sense to adopt a new feature. And it's not just new major versions, but smaller weekly patch releases contain gems like this from time to time.

Here to help,

Joel

P.S. Would you like some help getting your project set up with static analysis? The up-front investment will catch bugs over the life of the project.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.