如何为网站添加多语言模块并实现符合要求的多语言路由规则
多语言路由实现方案(英文默认无标识、阿拉伯语带前缀)
路由配置
在routes/web.php中定义带可选语言前缀的路由组,通过where方法限制前缀仅可取值为ar,默认空前缀对应英文:
use Illuminate\Support\Facades\Route; Route::prefix('{locale?}') ->where('locale', 'ar') ->middleware('setlocale') ->group(function () { // 所有业务路由都放在该分组内,示例如下 Route::get('/about', function () { return view('about'); })->name('about'); Route::get('/', function () { return view('home'); })->name('home'); });
setlocale中间件逻辑
在中间件中处理语言设置,同时处理英文场景下的路由参数隐藏:
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class SetLocale { public function handle(Request $request, Closure $next) { // 读取路由中的locale参数,无参数时默认使用英文 $locale = $request->route('locale') ?? 'en'; // 设置应用当前语言 app()->setLocale($locale); // 英文场景下移除路由中的locale参数,避免生成URL时自动携带/en前缀 if ($locale === 'en') { $request->route()->forgetParameter('locale'); } return $next($request); } }
效果验证
- 英文路由:访问
https://example.com/about,应用自动设置locale为en,URL无语言标识 - 阿拉伯语路由:访问
https://example.com/ar/about,应用自动设置locale为ar - 路由生成:直接调用
route('about')生成链接时,会自动根据当前locale判断是否携带/ar前缀,无需额外传参
内容的提问来源于stack exchange,提问作者Pouyabh
相关产品推荐
相关产品推荐

