First, you need to set the default locale and available locales in the config/app.php
file.
Example: Configuration in config/app.php
'locale' => 'en',
'fallback_locale' => 'en',
'locales' => ['en', 'es', 'fr'],
locale
: The default language of the application.fallback_locale
: The language used if the requested translation is not available.locales
: An array of available languages for your application.Laravel uses language files to store translation strings. These files are located in the resources/lang
directory. You can create language files for each language, such as en/messages.php
, es/messages.php
, etc.
Example: Creating Language Files
resources/lang/en/messages.php
)return [
'welcome' => 'Welcome to our platform!',
'login' => 'Login',
];
Spanish file (resources/lang/es/messages.php
)
return [
'welcome' => '¡Bienvenido a nuestra plataforma!',
'login' => 'Iniciar sesión',
];
You can use the __()
helper function to access translated strings in your Blade views.
Example: Using Translations in Blade
<h1>{{ __('messages.welcome') }}</h1>
<a href="#">{{ __('messages.login') }}</a>
You can switch the language dynamically by setting the locale using the App::setLocale()
method.
Example: Switching Languages in Controller
use Illuminate\Support\Facades\App;
public function switchLanguage($locale)
{
if (in_array($locale, ['en', 'es', 'fr'])) {
App::setLocale($locale);
}
return redirect()->back();
}
Laravel also provides localization for validation messages. You can create translation files for validation messages in the resources/lang/{locale}/validation.php
file.
Example: Creating Validation Messages
resources/lang/en/validation.php
)return [
'required' => 'The :attribute field is required.',
'email' => 'The :attribute must be a valid email address.',
];
Validation messages are automatically translated based on the current locale.
Example: Using Validation Messages in Blade
@error('email')
<div>{{ __('validation.email') }}</div>
@enderror
Laravel also provides localization for dates and times using the Carbon
package, which allows you to format dates in the selected locale.
Example: Formatting Dates in Different Locales
use Carbon\Carbon;
echo Carbon::now()->locale('es')->isoFormat('LLLL'); // Spanish formatted date
Laravel's localization features make it easy to translate and manage multi-language content within your application. By setting up language files, switching locales dynamically, and translating validation messages, you can create a multilingual experience for users across the globe.