How to use localization to build multi-language apps in Laravel
Create directories such as resources/lang/en and resources/lang/es and define messages.php language files; 2. Set the default language locale and alternate language fallback_locale in config/app.php; 3. Use App::setLocale() to dynamically switch languages, and combine middleware to automatically set them according to session or request headers; 4. Add {locale} prefix to route packets to implement multilingual URLs, and generate localized links in templates; 5. Use the __() function or @lang directive to call translation in controllers and views, supporting the plural form via trans_choice; 6. Optionally use the Artisan command or third-party package to manage translation; 7. In production environments, performance can be improved through cache configuration; by reasonably organizing language files, early detection of user language preferences, and providing switching mechanisms, combining middleware and routing packets, a clear multilingual application experience can be built.
Building multi-language apps in Laravel is straightforward when you use Laravel's built-in localization features. With proper localization setup, you can serve content in multiple languages based on user preferences or system settings. Here's how to use localization effectively in Laravel to build multi-language applications.
1. Set Up Language Files
Laravel stores language strings in the resources/lang
directory. Each language has its own subdirectory (eg, en
, es
, fr
). Start by creating these folders and defining language files as PHP arrays.
For example:
/resources /lang /en messages.php /es messages.php
In /resources/lang/en/messages.php
:
<?php Return [ 'welcome' => 'Welcome to our application', 'profile' => 'User Profile', ];
In /resources/lang/es/messages.php
:
<?php Return [ 'welcome' => 'Bienvenido a nuestra aplicación', 'profile' => 'Perfil de usuario', ];
You can now access these strings using the __()
helper or the @lang
Blade directive.
echo __('messages.welcome'); // Outputs: Welcome to our application
In Blade:
<h1>@lang('messages.welcome')</h1>
2. Configure the Default and Supported Languages
In config/app.php
, set your default locale:
'locale' => 'en', 'fallback_locale' => 'en',
You can support additional languages by simply adding more language directories under resources/lang
.
To allow dynamic switching, you'll need to store or detect the user's preferred language. Common approaches include:
- URL segments (eg,
/es/dashboard
) - Session-based preference
- User profile setting
- Browser Accept-Language header
3. Switch Languages Dynamically
To change the app language at runtime, use the App::setLocale()
method.
For example, in a middleware or controller:
use Illuminate\Support\Facades\App; Route::get('/language/{locale}', function ($locale) { if (in_array($locale, ['en', 'es', 'fr'])) { app()->setLocale($locale); session()->put('locale', $locale); } return redirect()->back(); });
You can also create a middleware to set the locale on every request:
// app/Http/Middleware/SetLocale.php class SetLocale { public function handle($request, $next) { $locale = session('locale') ?? $request->getPreferredLanguage(['en', 'es', 'fr']); app()->setLocale($locale); return $next($request); } }
Register the middleware in app/Http/Kernel.php
under web
.
4. Use Language-Specific Routes and URLs
To include the language in URLs, group routes with a locale prefix:
Route::group(['prefix' => '{locale}', 'middleware' => 'setLocale'], function () { Route::get('/dashboard', [DashboardController::class, 'index']); Route::get('/profile', [ProfileController::class, 'show']); });
In your Blade templates, generate localized URLs:
<a href="{{ route('dashboard', ['locale' => 'es']) }}">Ir al panel</a>
Make sure to handle the {locale}
parameter in your controllers or use a base controller to manage it.
5. Handle Translations in Views and Controllers
Use the __()
function anywhere in your code:
// In a controller return view('dashboard', [ 'title' => __('messages.profile') ]); // In validation messages $validated = $request->validate([ 'email' => 'required|email' ], [ 'email.required' => __('validation.email_required') ]);
For pluralization, Laravel supports it via language files:
// resources/lang/en/messages.php 'comments' => '{0} No comments|{1} One comment|[2,*] :count comments', // Usage echo trans_choice('messages.comments', $count);
6. Use Artisan to Manage Translations (Optional)
Laravel doesn't include a built-in translation manager, but you can create commands or use packages like laravel-lang/lang
or astrotomic/laravel-translatable
for advanced needs.
For simple apps, manually managing language files is sufficient.
7. Cache Translations in Production
In production, you can cache your language files for better performance:
php artisan config:cache
Note: Translation files aren't cached by default, but you can use packages or build a custom solution if needed.
Using Laravel's localization system makes it easy to support multiple languages. Focus on organizing language files clearly, detecting user language early, and providing a way to switch languages. With middleware and route grouping, you can build a clean, localized user experience.
Basically, it's not complex—just consistent file structure and smart locale switching.
The above is the detailed content of How to use localization to build multi-language apps in Laravel. 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)

Hot Topics



Create models and migration: Use phpartisanmake:modelPost-m to generate models and migration files, define the table structure and run phpartisanmigrate; 2. Basic CRUD operations: use Post::all(), find(), create(), save() and delete() methods to query, create, update and delete data; 3. Use Eloquent association: define belongsTo and hasMany relationships in the model, and use the with() method to preload the associated data to avoid N 1 query problems; 4. Eloquent query: use query constructor to chain calls such as where

Runphpartisannotifications:tableandmigratetosetupthedatabase.2.Createanotificationclassusingphpartisanmake:notificationNewMessageReceivedanddefinechannelsintheviamethod,dataintoDatabase,andreal-timebroadcastingintoBroadcast.3.Sendnotificationsvia$use

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

Create directories such as resources/lang/en and resources/lang/es and define messages.php language files; 2. Set the default language locale and alternate language fallback_locale in config/app.php; 3. Use App::setLocale() to dynamically switch languages, and combine middleware to automatically set them according to session or request headers; 4. Add {locale} prefix to implement multilingual URLs through routing packets, and generate localized links in templates; 5. Use the __() function or @lang instruction to call translation in controllers and views, supporting the plural form viatrans_choice

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

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-

UseCache::remember()tostoreEloquentqueryresultswithakeyandexpirationtime.2.Createdynamiccachekeysforparameterizedqueriestostoreseparateresults.3.InvalidatecacheusingCache::forget()ormodeleventswhendatachanges.4.UsecachetagswithRedisorMemcachedtogroup
