How to internationalize a Laravel application
Aug 22, 2025 pm 02:31 PMCreate language files: Create subdirectories for each language (such as en, es) in the resources/lang directory and add messages.php file, or use JSON file to store translation; 2. Set application language: read the request header Accept-Language through middleware or detect language through URL prefix, set the current language using app()->setLocale(), and register the middleware in Kernel.php; 3. Use translation functions: use __(), trans() or @lang in the view to get the translation content, and it is recommended to use __() that supports fallback; 4. Support parameters and plural: use placeholders such as: name in translation strings, and use trans_choice() to process plural forms such as '{0} No apples|{1} One apple|[2,*] :count apples'; 5. Configure fallback language: Set locale and fallback_locale in config/app.php to ensure fallback to the default language when translation is missing; 6. Optional performance optimization: The production environment can realize translation cache through third-party packages; 7. Front-end integration: Expose translation through the API interface or use framework-specific plug-ins to share language packages; Summary: Laravel internationalization requires structured management of language files, unified use of __() function, dynamically set the language with middleware, and handle parameters, plurals and fallbacks to achieve multilingual support.
Internationalizing a Laravel application allows you to serve content in multiple languages, making your app accessible to a global audience. Laravel provides solid built-in support for localization through language files and helper functions. Here's how to set it up properly.

1. Set Up Language Files
Laravel stores language strings in resources/lang
directory. Each language has its own subdirectory (eg, en
, es
, fr
).
Create language directories and files:

/resources /lang /en messages.php /es messages.php
Example: /resources/lang/en/messages.php
<?php Return [ 'welcome' => 'Welcome to our application', 'login' => 'Login', ];
Example: /resources/lang/es/messages.php

<?php Return [ 'welcome' => 'Bienvenido a nuestra aplicación', 'login' => 'Iniciar sesión', ];
You can also use JSON files for single translation strings (eg, resources/lang/es.json
), which Laravel supports natively.
2. Detect and Set the Application Locale
Laravel uses the App::setLocale()
method to switch languages. You need to determine the user's preferred language and set it early in the request lifecycle.
Option A: Middleware (Recommended)
Create a middleware to set the locale:
php artisan make:middleware SetLocale
In app/Http/Middleware/SetLocale.php
:
public function handle($request, \Closure $next) { $locale = $request->header('Accept-Language', 'en'); // Validate and sanitize locale (eg, 'en', 'es') $supportedLocales = ['en', 'es', 'fr']; if (! in_array($locale, $supportedLocales)) { $locale = 'en'; // fallback } app()->setLocale($locale); return $next($request); }
Register the middleware in app/Http/Kernel.php
under $middleware
or a route group.
Option B: URL-Based Locale
You can also pass the locale via the URL:
Route::get('/{locale}/welcome', function ($locale) { app()->setLocale($locale); return view('welcome'); });
Or use a route group:
Route::prefix('{locale}')->middleware('set.locale')->group(function () { Route::get('/welcome', [WelcomeController::class, 'index']); });
Then extract and store the locale in the session or user preferences.
3. Use Translation Functions in Views and Code
Laravel provides several helpers to retrieve translated strings.
Using __()
helper:
<h1>{{ __('messages.welcome') }}</h1> <p>{{ __('messages.login') }}</p>
Or with JSON translations:
<h1>{{ __('Welcome to our application') }}</h1>
Using @lang
Blade directive:
@lang('messages.welcome')
Note:
@lang
does not fall back to other languages ??and is less flexible than__()
, so__()
is preferred.
Passing Parameters
For dynamic translations:
// Language file 'hello' => 'Hello, :name',
{{ __('messages.hello', ['name' => 'John']) }}
4. Pluralization and Choice
Laravel supports pluralization using the trans_choice()
function.
Example in language file:
'apples' => '{0} No apples|{1} One apple|[2,*] :count apples',
Or using placeholders:
'apples' => 'One apple|:count apples',
Usage:
{{ trans_choice('messages.apples', 3) }}
This outputs: 3 apples
.
5. Fallback and Missing Translations
Laravel falls back to the default locale (defined in config/app.php
) when a translation is missing.
Ensure your config/app.php
includes:
'locale' => 'en', 'fallback_locale' => 'en',
You can log or handle missing translations by extending Laravel's translator, but by default, it returns the key or fallback.
6. Caching Translations (Optional)
In production, you can cache language files for performance:
php artisan config:cache php artisan route:cache
While Laravel doesn't provide lang:cache
by default, you can use packages like barryvdh/laravel-translation-manager
or implement a custom cache layer if needed.
7. JavaScript Integration (Optional)
If your frontend needs translations, consider using packages like spatie/laravel-translatable
or inertiajs/inertia
with shared props, or expose translations via a secure endpoint:
Route::get('/translations/{locale}', function ($locale) { $translations = translate('messages', [], $locale); return response()->json($translations); });
Or use a package like vue-i18n
/ laravel-vue-i18n
if using Vue.
Summary
To internationalize a Laravel app:
- Store translations in
resources/lang/{locale}/
- Use
__()
ortrans()
helpers in views and controllers - Detect language via header, URL, or user settings
- Set locale using middleware
- Support parameters and pluralization
- Handle fallbacks and missing keys
It's not complex, but consistency in structure and planning your locales upfront makes maintenance easier.
The above is the detailed content of How to internationalize a Laravel application. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PolymorphicrelationshipsinLaravelallowamodellikeCommentorImagetobelongtomultiplemodelssuchasPost,Video,orUserusingasingleassociation.2.Thedatabaseschemarequires{relation}_idand{relation}_typecolumns,exemplifiedbycommentable_idandcommentable_typeinaco

Yes,youcancreateasocialnetworkwithLaravelbyfollowingthesesteps:1.SetupLaravelusingComposer,configurethe.envfile,enableauthenticationviaBreeze/Jetstream/Fortify,andrunmigrationsforusermanagement.2.Implementcorefeaturesincludinguserprofileswithavatarsa

Laravel's TaskScheduling system allows you to define and manage timing tasks through PHP, without manually editing the server crontab, you only need to add a cron task that is executed once a minute to the server: *cd/path-to-your-project&&phpartisanschedule:run>>/dev/null2>&1, and then all tasks are configured in the schedule method of the App\Console\Kernel class; 1. Defining tasks can use command, call or exec methods, such as $schedule-

Create language files: Create subdirectories for each language (such as en, es) in the resources/lang directory and add messages.php file, or use JSON file to store translation; 2. Set application language: read the request header Accept-Language through middleware or detect language through URL prefix, set the current language using app()->setLocale(), and register the middleware in Kernel.php; 3. Use translation functions: use __(), trans() or @lang in the view, and use __() that supports fallback; 4. Support parameters and plural: Use placeholders in translation strings such as: n

Using Laravel to build a mobile backend requires first installing the framework and configuring the database environment; 2. Define API routes in routes/api.php and return a JSON response using the resource controller; 3. Implement API authentication through LaravelSanctum to generate tokens for mobile storage and authentication; 4. Verify file type when uploading files and store it on public disk, and create soft links for external access; 5. The production environment requires HTTPS, set current limits, configure CORS, perform API version control and optimize error handling. It is also recommended to use API resources, paging, queues and API document tools to improve maintainability and performance. Use Laravel to build a safe,

LaravelusesMonologtologmessagesviatheLogfacade,withdefaultlogsstoredinstorage/logs/laravel.log.Configurechannelsinconfig/logging.phptocontroloutput;thedefaultstackchannelaggregatesmultiplehandlerslikesingle,whichwritestoafile.UseLog::info(),Log::warn

Ensure that there is a remember_token column in the user table. Laravel's default migration already includes this field. If not, it will be added through migration; 2. Add a check box with name remember in the login form to provide the "Remember Me" option; 3. Pass the remember parameter to the Auth::attempt() method during manual authentication to enable persistent login; 4. "Remember Me" lasts for 5 years by default, and can be customized through the remember_for configuration item in config/auth.php; 5. Laravel automatically invalidates remember_token when password changes or user deletes. It is recommended to use HTTPS to ensure security in the production environment; 6

ACountrycanaccessallPoststhroughUsersusinghasManyThrough.Forexample,withcountries,users,andpoststableslinkedbyforeignkeys,theCountrymodeldefinesahasManyThroughrelationshiptoPostviaUser,enablingefficientindirectdataretrievalacrosstwoone-to-manyrelatio
