Localization
Introduction
Lacelium's localization features provide a convenient way to retrieve strings in various languages, allowing you to easily support multiple languages within your application.
Translation strings are stored in files within the resources/lang directory. Within this directory, there should be a subdirectory for each language supported by the application:
/resources
/lang
/en
messages.php
validation.php
/es
messages.php
validation.php
/fr
messages.php
Configuring the Locale
The default language for your application is configured in the config/app.php configuration file's locale option. You may modify this value to suit the needs of your application:
// config/app.php
return [
'locale' => 'en',
'fallback_locale' => 'en',
];
Determining the Locale at Runtime
You may change the active language at runtime using the app_set_locale helper function or inspect the current language using app_locale():
// Check current locale
$currentLocale = app_locale(); // 'en'
// Switch active locale
app_set_locale('es');
You can also create a lightweight route middleware to inspect user session preferences or the browser's Accept-Language HTTP request header to configure the locale on each request:
// In custom middleware
$locale = $request->getSession()->get('locale', 'en');
app_set_locale($locale);
Defining Translation Strings
Translation files return an array of keyed strings. For example, in resources/lang/en/messages.php:
<?php
return [
'welcome' => 'Welcome to our application!',
'greeting' => 'Hello, :name! You have :count unread messages.',
];
Retrieving Translation Strings
You may retrieve lines from language files using the global __ or trans helper functions. The translation method accepts the file and key of the translation line as its first argument:
echo __('messages.welcome');
Replacing Parameters in Translation Strings
If you have defined place-holders in your translation strings, you may pass an array of replacements as the second argument to the __ function:
echo __('messages.greeting', ['name' => 'Dayle', 'count' => 5]);
// Output: Hello, Dayle! You have 5 unread messages.
In Twig Templates
Lacelium automatically exposes translation filters and helpers directly inside your Twig views:
<h1>messages.welcome</h1>
<p>messages.greeting</p>
Fallback Languages
When a translation string does not exist in the active locale, Lacelium will automatically attempt to locate the string in the fallback_locale defined in config/app.php. If the line is not found in either locale, the raw translation key will be returned.
Next Steps
- Secure your application with Security Safeguards.
- Explore database models in Database Manager.
- Build modern interfaces with SPA Experience.