0
0
Laravelframework~5 mins

Config files and access in Laravel

Choose your learning style9 modes available
Introduction

Config files store settings for your Laravel app in one place. This helps you change app behavior without editing code everywhere.

You want to set database connection details like host and username.
You need to change app settings like timezone or locale.
You want to store API keys or service credentials safely.
You want to toggle features on or off without changing code.
You want to organize settings for mail, cache, or queue services.
Syntax
Laravel
<?php

return [
    'key' => 'value',
    'nested' => [
        'subkey' => 'subvalue',
    ],
];
Config files are PHP files that return an array of settings.
Each config file is stored in the config/ folder.
Examples
A simple config file with app name and debug mode.
Laravel
<?php

return [
    'app_name' => 'My Laravel App',
    'debug' => true,
];
Nested array for database settings.
Laravel
<?php

return [
    'database' => [
        'host' => '127.0.0.1',
        'port' => 3306,
    ],
];
Using env() to get sensitive info from environment variables.
Laravel
<?php

return [
    'services' => [
        'mailgun' => [
            'domain' => env('MAILGUN_DOMAIN'),
            'secret' => env('MAILGUN_SECRET'),
        ],
    ],
];
Sample Program

This example shows a config file example.php with two keys. The route /greet reads these values using Config::get() and returns a greeting message.

Laravel
<?php

// config/example.php
return [
    'greeting' => 'Hello',
    'audience' => 'World',
];

// In a Laravel controller or route closure
use Illuminate\Support\Facades\Config;

Route::get('/greet', function () {
    $greeting = Config::get('example.greeting');
    $audience = Config::get('example.audience');
    return "$greeting, $audience!";
});
OutputSuccess
Important Notes

Use Config::get('file.key') to read config values anywhere in your app.

Use env() in config files to keep secrets out of code and use environment variables instead.

After changing config files, you may need to clear config cache with php artisan config:clear.

Summary

Config files hold app settings in config/ as PHP arrays.

Access config values with Config::get('file.key').

Use environment variables for sensitive info with env().