config() helper, Config facade, config cache
Concept
The config() helper and Config facade provide access to Laravel's configuration system. Config files in config/ return PHP arrays; these arrays are loaded at boot time and merged into a single configuration repository.
config() usage:
config('key'): Get a value. Returns null if not found.config('key', 'default'): Get a value with a default.config(['key' => 'value']): Set a value at runtime (NOT persisted, affects current request only).config()->all(): Get all configuration as a nested array.
Dot notation: config('database.connections.mysql.host') traverses the nested config array. database → connections → mysql → host.
Where config files live: All files in config/ are auto-loaded. config/app.php → accessible as config('app.*'). A custom config/mypackage.php → accessible as config('mypackage.*').
config:cache: Combines all config files into a single bootstrap/cache/config.php file. This is the production optimization. After caching: config() reads from the cache file, .env is NOT read (so env() outside config files returns null). Run php artisan config:clear to remove the cache.
Dynamic config (runtime): config(['services.stripe.key' => $newKey]) changes a config value for the current request. Useful in tests. Not persisted between requests.
Code Example
<?php
// config/services.php
return [
'stripe' => [
'key' => env('STRIPE_KEY'),
'secret' => env('STRIPE_SECRET'),
'webhook_secret' => env('STRIPE_WEBHOOK_SECRET'),
],
'mailchimp' => [
'api_key' => env('MAILCHIMP_API_KEY'),
'list_id' => env('MAILCHIMP_LIST_ID'),
],
];<?php
// Accessing config values
$stripeKey = config('services.stripe.key');
$appName = config('app.name', 'Default App');
$dbDriver = config('database.default'); // 'mysql' or 'sqlite'
$allConfig = config()->all();
// Config facade
use Illuminate\Support\Facades\Config;
$key = Config::get('services.stripe.key');
Config::set('services.stripe.key', 'test_key'); // runtime set (not persisted)
// Runtime config for testing
// In a test: override config to use test values
public function setUp(): void
{
parent::setUp();
Config::set('mail.default', 'log'); // use log driver in tests
Config::set('services.stripe.key', 'test_key');
$this->withoutVite(); // another test helper
}
// Helper: config() with array sets multiple values
config([
'mail.default' => 'array',
'services.stripe.key' => 'sk_test_123',
]);
// Best practice — centralize env() calls in config files
// config/myfeature.php
return [
'enabled' => env('MYFEATURE_ENABLED', true),
'api_url' => env('MYFEATURE_API_URL', 'https://api.example.com'),
'timeout' => (int) env('MYFEATURE_TIMEOUT', 30),
];
// Then in service classes — config() not env()
$timeout = config('myfeature.timeout'); // works even after config:cache