Table of Contents
1. Set Up Language Files
2. Configure the Default and Supported Languages
3. Switch Languages ​​Dynamically
4. Use Language-Specific Routes and URLs
5. Handle Translations in Views and Controllers
6. Use Artisan to Manage Translations (Optional)
7. Cache Translations in Production
Home PHP Framework Laravel How to use localization to build multi-language apps in Laravel

How to use localization to build multi-language apps in Laravel

Sep 02, 2025 am 04:54 AM

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.

How to use localization to build multi-language apps in Laravel

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 [
    &#39;welcome&#39; => &#39;Welcome to our application&#39;,
    &#39;profile&#39; => &#39;User Profile&#39;,
];

In /resources/lang/es/messages.php :

 <?php

Return [
    &#39;welcome&#39; => &#39;Bienvenido a nuestra aplicación&#39;,
    &#39;profile&#39; => &#39;Perfil de usuario&#39;,
];

You can now access these strings using the __() helper or the @lang Blade directive.

 echo __(&#39;messages.welcome&#39;); // Outputs: Welcome to our application

In Blade:

 <h1>@lang(&#39;messages.welcome&#39;)</h1>

2. Configure the Default and Supported Languages

In config/app.php , set your default locale:

 &#39;locale&#39; => &#39;en&#39;,
&#39;fallback_locale&#39; => &#39;en&#39;,

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(&#39;/language/{locale}&#39;, function ($locale) {
    if (in_array($locale, [&#39;en&#39;, &#39;es&#39;, &#39;fr&#39;])) {
        app()->setLocale($locale);
        session()->put(&#39;locale&#39;, $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(&#39;locale&#39;) ?? $request->getPreferredLanguage([&#39;en&#39;, &#39;es&#39;, &#39;fr&#39;]);

        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([&#39;prefix&#39; => &#39;{locale}&#39;, &#39;middleware&#39; => &#39;setLocale&#39;], function () {
    Route::get(&#39;/dashboard&#39;, [DashboardController::class, &#39;index&#39;]);
    Route::get(&#39;/profile&#39;, [ProfileController::class, &#39;show&#39;]);
});

In your Blade templates, generate localized URLs:

 <a href="{{ route(&#39;dashboard&#39;, [&#39;locale&#39; => &#39;es&#39;]) }}">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(&#39;dashboard&#39;, [
    &#39;title&#39; => __(&#39;messages.profile&#39;)
]);

// In validation messages
$validated = $request->validate([
    &#39;email&#39; => &#39;required|email&#39;
], [
    &#39;email.required&#39; => __(&#39;validation.email_required&#39;)
]);

For pluralization, Laravel supports it via language files:

 // resources/lang/en/messages.php
&#39;comments&#39; => &#39;{0} No comments|{1} One comment|[2,*] :count comments&#39;,

// Usage
echo trans_choice(&#39;messages.comments&#39;, $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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use Eloquent in Laravel How to use Eloquent in Laravel Aug 21, 2025 pm 02:30 PM

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

How to build a notification system with Laravel How to build a notification system with Laravel Sep 01, 2025 am 08:15 AM

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

How to work with Polymorphic Relationships in Laravel How to work with Polymorphic Relationships in Laravel Aug 25, 2025 am 10:56 AM

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

How to use localization to build multi-language apps in Laravel How to use localization to build multi-language apps in Laravel Sep 02, 2025 am 04:54 AM

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

How to internationalize a Laravel application How to internationalize a Laravel application Aug 22, 2025 pm 02:31 PM

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

How to create a social network with Laravel How to create a social network with Laravel Sep 01, 2025 am 06:39 AM

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

How to use Laravel's Task Scheduling How to use Laravel's Task Scheduling Aug 31, 2025 am 06:07 AM

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-

How to cache Eloquent queries in Laravel How to cache Eloquent queries in Laravel Aug 25, 2025 am 09:25 AM

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

See all articles