Configuration and localisation
The database address, payment keys and interface language differ between your computer and the server. Laravel separates such values from the code: secrets live in .env, settings in the config folder, interface texts in translation files.
The .env file
.env holds values that differ between environments. It does not go into the repository:
APP_NAME="My blog"
APP_ENV=local
APP_DEBUG=true
STRIPE_SECRET=sk_test_123Configuration files
Code does not read .env values directly. They are pulled into the files of the config folder with the env() function:
// config/services.php
return [
'stripe' => [
'secret' => env('STRIPE_SECRET'),
'currency' => env('STRIPE_CURRENCY', 'usd'),
],
];The second argument of env() is a default value.
Reading settings
Everywhere in the application settings are read with the config() function. The path to a value is written with dots: the file name, then the keys:
$secret = config('services.stripe.secret');
$name = config('app.name');
$timezone = config('app.timezone', 'UTC');Your own settings
Just create a file in the config folder:
// config/blog.php
return [
'posts_per_page' => 15,
'allow_comments' => env('BLOG_COMMENTS', true),
];$posts = Post::latest()->paginate(config('blog.posts_per_page'));The environment
if (app()->environment('production')) {
// on the production server only
}
if (app()->isLocal()) {
// during development only
}Translation files
Interface texts are kept in the lang folder. A command creates it:
php artisan lang:publishEach language has its own folder with array files:
// lang/en/messages.php
return [
'welcome' => 'Welcome, :name!',
'posts' => '{0} No posts|{1} :count post|[2,*] :count posts',
];Printing a translation
The __() function returns the text in the current language. Values replace the words that start with a colon:
<h1>{{ __('messages.welcome', ['name' => $user->name]) }}</h1>
<p>{{ trans_choice('messages.posts', $count, ['count' => $count]) }}</p>trans_choice() picks the word form by the number.
Switching the language
The default language is set by APP_LOCALE in .env. For a particular request it is changed in middleware:
use Illuminate\Support\Facades\App;
public function handle(Request $request, Closure $next)
{
App::setLocale($request->segment(1) === 'fr' ? 'fr' : 'en');
return $next($request);
}Common mistake
After php artisan config:cache the env() function returns null outside the config folder: the .env file is no longer read. So use only config() in controllers, models and templates, and env() exclusively in configuration files.