如何使用本地化在Laravel構建多語言應用程序
創建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. 生產環境中可通過緩存配置提升性能;通過合理組織語言文件、早期檢測用戶語言偏好並提供切換機制,結合中間件和路由分組,即可構建清晰的多語言應用體驗。
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.
以上是如何使用本地化在Laravel構建多語言應用程序的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

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

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

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

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(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

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

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

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

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

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