目錄
Setting up language files
Switching between languages dynamically
Translating URLs and routes
Managing translation keys in Blade templates
首頁 php框架 Laravel 在Laravel應用程序中添加多語言支持

在Laravel應用程序中添加多語言支持

Jul 03, 2025 am 01:17 AM
laravel 多語言

Laravel應用實現多語言支持的核心方法包括:設置語言文件、動態切換語言、翻譯URL路由及管理Blade模板中的翻譯鍵。首先,將各語言字符串組織在/resources/lang目錄下的對應文件夾(如en、es、fr)中,並通過返回關聯數組定義翻譯內容;2. 通過\_\_()輔助函數調用翻譯鍵值,並使用App::setLocale()結合會話或路由參數實現語言切換;3. 對於翻譯URL,可通過帶前綴的路由組分別為不同語言定義路徑,或動態映射語言文件中的路由別名;4. 在Blade模板中保持翻譯鍵簡潔並利用Laravel對占位符和復數形式的支持提升翻譯靈活性。這些步驟共同構建起結構清晰且易於維護的多語言系統。

Adding multilingual support to a Laravel application

Adding multilingual support to a Laravel application isn't too complicated, but it does require some planning and setup. The core idea is to make your app able to serve content in multiple languages based on user preference or browser settings.

Adding multilingual support to a Laravel application

Laravel has built-in localization features that you can use right out of the box — no need for extra packages unless you want more advanced functionality.

Adding multilingual support to a Laravel application

Setting up language files

The first thing you'll want to do is organize your language strings. Laravel uses the lang directory for this. Each language gets its own folder (like en , es , fr ), and inside each folder, you create PHP files that return associative arrays of key-value pairs.

For example:

Adding multilingual support to a Laravel application
 /resources/lang/en/messages.php
/resources/lang/es/messages.php

Each file might look like this:

 // en/messages.php
return [
    'welcome' => 'Welcome to our site!',
];
 // es/messages.php
return [
    'welcome' => '¡ Bienvenido a nuestro sitio!',
];

You can then display these messages using the __() helper function in views or controllers:

 <h1>{{ __(&#39;messages.welcome&#39;) }}</h1>

This method keeps your strings organized and makes switching between languages easier later.


Switching between languages dynamically

To let users switch languages, you'll typically set a session variable or use a route parameter like /es/home . Laravel doesn't handle this automatically, so you'll need to write a bit of logic.

A common approach is to create a middleware that checks the URL prefix or a cookie/session value and sets the app locale accordingly.

Here's a basic example of how to do it via a controller or middleware:

 App::setLocale($locale); // $locale could be &#39;en&#39;, &#39;es&#39;, etc.

You can also add routes for switching the language:

 Route::get(&#39;/language/{locale}&#39;, function ($locale) {
    App::setLocale($locale);
    session([&#39;locale&#39; => $locale]);
    return redirect()->back();
});

And in your view, show links for available languages:

 @foreach([&#39;en&#39;, &#39;es&#39;, &#39;fr&#39;] as $lang)
    <a href="{{ url("/language/$lang") }}">{{ strtoupper($lang) }}</a>
@endforeach

Make sure to check the session or user preference early in the request lifecycle so the correct language loads before rendering views.


Translating URLs and routes

If you want your URLs to be translated (eg, /about becomes /sobre in Spanish), things get a little trickier. Laravel doesn't support translated route names directly, but you can define separate routes for each language.

One way to manage this is by using route groups with different prefixes:

 Route::prefix(&#39;en&#39;)->group(function () {
    Route::get(&#39;/about&#39;, [PageController::class, &#39;about&#39;]);
});

Route::prefix(&#39;es&#39;)->group(function () {
    Route::get(&#39;/sobre&#39;, [PageController::class, &#39;about&#39;]);
});

Alternatively, you can store translations of route slugs in language files and map them dynamically. But that requires more complex routing logic and possibly a database lookup if the slugs are dynamic (like blog posts).

Keep in mind: translated URLs improve SEO for each language version, but they take more maintenance.


Managing translation keys in Blade templates

When working with Blade templates, it's best to keep your translation keys short and descriptive. For example:

 {{ __(&#39;auth.login&#39;) }}

Avoid putting entire sentences directly in the template — it makes managing translations harder over time.

Also, if you're dealing with pluralization or placeholders, Laravel supports that too:

 __(&#39;messages.items&#39;, [&#39;count&#39; => $items->count()])

In your language file:

 // en/messages.php
&#39;items&#39; => &#39;{0} No items found.|{1} One item found.|[2,*] :count items found.&#39;

This helps when your app needs to display slightly different text depending on context or data.


Basically, setting up multilingual support in Laravel comes down to organizing your language files, handling locale changes, and deciding whether you need translated URLs. It's not overly complex, but it does require attention to structure and consistency.

以上是在Laravel應用程序中添加多語言支持的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

Rimworld Odyssey溫度指南和Gravtech
1 個月前 By Jack chen
初學者的Rimworld指南:奧德賽
1 個月前 By Jack chen
PHP變量範圍解釋了
3 週前 By 百草
撰寫PHP評論的提示
3 週前 By 百草
在PHP中評論代碼
3 週前 By 百草

熱工具

記事本++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 教程
1603
29
PHP教程
1508
276
Laravel中的配置緩存是什麼? Laravel中的配置緩存是什麼? Jul 27, 2025 am 03:54 AM

Laravel的配置緩存通過合併所有配置文件為一個緩存文件來提升性能。在生產環境中啟用配置緩存可減少每次請求時的I/O操作和文件解析,從而加快配置加載速度;1.應在部署應用、配置穩定且無需頻繁更改時啟用;2.啟用後修改配置需重新運行phpartisanconfig:cache才會生效;3.避免在配置文件中使用依賴運行時條件的動態邏輯或閉包;4.排查問題時應先清除緩存、檢查.env變量並重新緩存。

如何在Laravel中創建輔助文件? 如何在Laravel中創建輔助文件? Jul 26, 2025 am 08:58 AM

Createahelpers.phpfileinapp/HelperswithcustomfunctionslikeformatPrice,isActiveRoute,andisAdmin.2.Addthefiletothe"files"sectionofcomposer.jsonunderautoload.3.Runcomposerdump-autoloadtomakethefunctionsgloballyavailable.4.Usethehelperfunctions

如何在Laravel測試中模擬對象? 如何在Laravel測試中模擬對象? Jul 27, 2025 am 03:13 AM

UseMockeryforcustomdependenciesbysettingexpectationswithshouldReceive().2.UseLaravel’sfake()methodforfacadeslikeMail,Queue,andHttptopreventrealinteractions.3.Replacecontainer-boundserviceswith$this->mock()forcleanersyntax.4.UseHttp::fake()withURLp

如何在Laravel中實施推薦系統? 如何在Laravel中實施推薦系統? Aug 02, 2025 am 06:55 AM

創建referrals表記錄推薦關係,包含推薦人、被推薦人、推薦碼及使用時間;2.在User模型中定義belongsToMany和hasMany關係以管理推薦數據;3.用戶註冊時生成唯一推薦碼(可通過模型事件實現);4.註冊時通過查詢參數捕獲推薦碼,驗證後建立推薦關係並防止自薦;5.當被推薦用戶完成指定行為(如下單)時觸發獎勵機制;6.生成可分享的推薦鏈接,可使用Laravel簽名URL增強安全性;7.在儀表板展示推薦統計信息,如總推薦數和已轉化數;必須確保數據庫約束、會話或Cookie持久化、

如何運行Laravel項目? 如何運行Laravel項目? Jul 28, 2025 am 04:28 AM

checkphp> = 8.1,作曲家和韋伯佛; 2.cleteproeateprojectandruncomposerinstall; 3.copy.env.exampleto.envandrunphpartisankey :生成; 4.setDatabasecredentialsin.envandrunphpartisanmigrate-seed; 5.StartServerServerWithPhpartisanServe; 6.optionallyrunnnpmins

如何在Laravel中播種數據庫? 如何在Laravel中播種數據庫? Jul 28, 2025 am 04:23 AM

創建seeder文件:使用phpartisanmake:seederUserSeeder生成seeder類,並在run方法中通過模型工廠或數據庫查詢插入數據;2.在DatabaseSeeder中調用其他seeder:通過$this->call()按順序註冊UserSeeder、PostSeeder等,確保依賴關係正確;3.運行seeder:執行phpartisandb:seed運行所有註冊的seeder,或使用phpartisanmigrate:fresh--seed重置並重新填充數據;4

如何使用Laravel構建REST API? 如何使用Laravel構建REST API? Jul 30, 2025 am 03:41 AM

創建新Laravel項目並啟動服務;2.生成模型、遷移和控制器並運行遷移;3.在routes/api.php中定義RESTful路由;4.在PostController中實現增刪改查方法並返回JSON響應;5.使用Postman或curl測試API功能;6.可選地通過Sanctum添加API認證;最終得到一個結構清晰、功能完整且可擴展的LaravelRESTAPI,適用於實際應用。

使用Laravel中的活動和聽眾。 使用Laravel中的活動和聽眾。 Jul 26, 2025 am 08:21 AM

在Laravel中使用事件和監聽器是一種解耦主邏輯的有效方式。 1.創建事件和監聽器可通過Artisan命令生成並綁定至EventServiceProvider或啟用自動發現機制。 2.實際使用中需注意一個事件可對應多個監聽器、隊列失敗重試策略、保持監聽器輕量及註冊事件訂閱者。 3.測試調試時應確認事件觸發、監聽器綁定、隊列驅動狀態,並設置QUEUE_CONNECTION=sync以同步執行便於排查問題。 4.高級技巧包括根據條件動態控制監聽器執行或註冊,但建議進階用戶使用。掌握這些要點有助於提升代碼維

See all articles