目錄
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
首頁 php框架 Laravel 如何使用本地化在Laravel構建多語言應用程序

如何使用本地化在Laravel構建多語言應用程序

Sep 02, 2025 am 04:54 AM

創建resources/lang/en 和resources/lang/es 等目錄並定義messages.php 語言文件;2. 在config/app.php 中設置默認語言locale 和備用語言fallback_locale;3. 使用App::setLocale() 動態切換語言,結合中間件根據會話或請求頭自動設置;4. 通過路由分組添加{locale} 前綴實現多語言URL,並在模板中生成本地化鏈接;5. 在控制器和視圖中使用__() 函數或@lang 指令調用翻譯,支持複數形式via trans_choice;6. 可選使用Artisan 命令或第三方包管理翻譯;7. 生產環境中可通過緩存配置提升性能;通過合理組織語言文件、早期檢測用戶語言偏好並提供切換機制,結合中間件和路由分組,即可構建清晰的多語言應用體驗。

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.

以上是如何使用本地化在Laravel構建多語言應用程序的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Stock Market GPT

Stock Market GPT

人工智慧支援投資研究,做出更明智的決策

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

如何與Laravel中的多態關係一起工作 如何與Laravel中的多態關係一起工作 Aug 25, 2025 am 10:56 AM

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

如何與Laravel建立社交網絡 如何與Laravel建立社交網絡 Sep 01, 2025 am 06:39 AM

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

如何使用Laravel構建通知系統 如何使用Laravel構建通知系統 Sep 01, 2025 am 08:15 AM

runphpartisannotifications:tableandmigratetosetupthedatabase.2.CreateAnotificationClassusingphpartisanMake:NotificationNewMessageReceivedAndDefineChannelsinthelsintheviamethod,dataintodatabase,dataintodatabase,andreal timebroadcastingIntnotnotification Via $ use

如何使用本地化在Laravel構建多語言應用程序 如何使用本地化在Laravel構建多語言應用程序 Sep 02, 2025 am 04:54 AM

創建resources/lang/en和resources/lang/es等目錄並定義messages.php語言文件;2.在config/app.php中設置默認語言locale和備用語言fallback_locale;3.使用App::setLocale()動態切換語言,結合中間件根據會話或請求頭自動設置;4.通過路由分組添加{locale}前綴實現多語言URL,並在模板中生成本地化鏈接;5.在控制器和視圖中使用__()函數或@lang指令調用翻譯,支持複數形式viatrans_choice

如何使用Laravel的任務計劃 如何使用Laravel的任務計劃 Aug 31, 2025 am 06:07 AM

Laravel的TaskScheduling系統允許通過PHP定義和管理定時任務,無需手動編輯服務器crontab,只需在服務器添加一條每分鐘執行一次的cron任務:*cd/path-to-your-project&&phpartisanschedule:run>>/dev/null2>&1,隨後所有任務均在App\Console\Kernel類的schedule方法中配置;1.定義任務可使用command、call或exec方法,如$schedule-

如何緩存Laravel雄辯的查詢 如何緩存Laravel雄辯的查詢 Aug 25, 2025 am 09:25 AM

usecache ::記住()tostoreeloquentqueryresultswithakeyandexpiration time.2.CreatedyNamicCacheKeySforParameterParameterizedquermeterizedquermeTsostostostoresepareteresults.3.invalidatatecacheusingscache :: nove()heven()ormodeleventswhendatachanges.4.usecachetagswitheTagswitheDissredisemormemormemememcachedttrogrouxpogrouxpogrouxpogrouff

如何使用Laravel構建移動應用程序後端 如何使用Laravel構建移動應用程序後端 Sep 02, 2025 am 08:34 AM

使用Laravel構建移動端后端需先安裝框架並配置數據庫環境;2.在routes/api.php中定義API路由並使用資源控制器返回JSON響應;3.通過LaravelSanctum實現API認證,生成令牌供移動端存儲和認證;4.處理文件上傳時驗證文件類型並存儲至public磁盤,同時創建軟鏈接供外部訪問;5.生產環境需啟用HTTPS、設置限流、配置CORS、進行API版本控制並優化錯誤處理,同時建議使用API​​資源、分頁、隊列和API文檔工具以提升可維護性和性能。使用Laravel可構建安全、可

如何在拉拉維爾(Laravel)中以隊列運行背景工作 如何在拉拉維爾(Laravel)中以隊列運行背景工作 Aug 30, 2025 am 04:49 AM

SetQUEUE_CONNECTION=databaseorredisin.envforbackgroundprocessing.2.Runphpartisanqueue:tableandmigratetocreatethejobstable;configureRedisifneeded.3.Generateajobwithphpartisanmake:jobProcessPodcastandimplementthehandle()method.4.DispatchthejobusingProc

See all articles