Building web applications for a global audience requires Localization (i18n) — the ability to display user interfaces in multiple spoken languages (e.g. English, Hindi, Spanish, French, German). Laravel provides native support for two translation file structures: short-key PHP arrays and full-string JSON translation dictionaries.
JSON translation files use the default English translation as the dictionary key itself. This means you do not have to invent artificial nested keys (like messages.auth.errors.invalid) for every sentence. Create translation files directly in lang/ (or resources/lang/):
// lang/hi.json (Hindi Translation)
{
"Welcome to our tutorial portal": "हमारे ट्यूटोरियल पोर्टल में आपका स्वागत है",
"Login to your account": "अपने खाते में लॉगिन करें",
"Hello, :name!": "नमस्ते, :name!",
"You have :count pending assignments": "आपके पास :count लंबित असाइनमेंट हैं"
}
// lang/es.json (Spanish Translation)
{
"Welcome to our tutorial portal": "Bienvenido a nuestro portal de tutoriales",
"Login to your account": "Inicie sesión en su cuenta"
}
To render localized text in Blade, use the __('String') helper function or the @lang directive:
<!-- Using double curly brackets with __() helper -->
<h1>{{ __('Welcome to our tutorial portal') }}</h1>
<!-- Passing dynamic parameters -->
<p>{{ __('Hello, :name!', ['name' => auth()->user()->name]) }}</p>
<!-- Pluralization with trans_choice -->
<p>{{ trans_choice('There is one notification|There are :count notifications', $unreadCount, ['count' => $unreadCount]) }}</p>
To allow visitors to click a language selector and persist their choice across the entire session, create a custom middleware:
php artisan make:middleware SetLocaleFromSession
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
class SetLocaleFromSession
{
public function handle(Request $request, Closure $next)
{
// 1. Check if user has a language saved in session
$locale = session('locale', config('app.locale'));
// 2. Validate locale against allowed whitelist
if (in_array($locale, ['en', 'hi', 'es', 'fr'])) {
App::setLocale($locale);
}
return $next($request);
}
}
Create a route that updates the user's session locale:
Route::get('/language/{locale}', function (string $locale) {
if (in_array($locale, ['en', 'hi', 'es', 'fr'])) {
session(['locale' => $locale]);
}
return back();
})->name('language.switch');
Now, whenever a user clicks <a href="{{ route('language.switch', 'hi') }}">हिन्दी</a>, the entire portal switches to Hindi instantly!
Broaden your backend architecture, REST API design, and enterprise production engineering expertise:
Render localized strings using @lang() directives and JSON translation files.
Create a SetLocale middleware to switch App::setLocale() from user preferences.
Localize validation error feedback in resources/lang/{locale}/validation.php.
Inspect multi-currency and multi-language support in our production capstone code.