首页 > 解决方案 > 使用 Laravel 通过 url 参数在运行时更改表名

问题描述

我想根据我的 URL 的 i18N 参数更改一些表名,如下所示:https://localhost/frhttps://localhost/en,...表名将如下所示: tablename_fr, tablename_en 我想做这是为了尽可能简化我网站的 i18n 过渡。我怎么能用 Laravel 做到这一点?您是否发现该系统存在性能问题?也许它会扰乱 Laravel/Eloquent 缓存?

标签: databaselaraveleloquentinternationalization

解决方案


您可以为表添加 lang 文件。

# resources/lang/en/tables
// English names for tables
return [
    'cars' => 'cars'
    'computers' => 'computers'
]
# resources/lang/fr/tables.php
// French names for tables
return [
    'cars' => 'voitures'
    'computers' => 'ordinateurs'
]

然后在您的视图中,您可以使用url()帮助程序形成 url。想象一下我们有$car一个id: 1

url(__('tables.cars').'/'.$car->id)
// if App::getLocale() === 'en', it returns /cars/1
// if App::getLocale() === 'fr', it returns /voitures/1
// if App::getLocale() === 'es', it returns /cars/1 because there's no 'es' lang file in this example and by default, 'en' is the fallback language.

不过,您确实需要设置其他路由规则。

或者,您可以设置额外的 i18n 路由,然后调用 route() 助手

# routes/web.php
// You could group the routes to add a prefix, but the idea is the same
Route::get('cars/{car}', CarController@show)->name('en.car.show');
Route::get('voitures/{car}', CarController@show)->name('fr.car.show');
# in a view
route(App::getLocale().'.car.show', [$car->id]) 
// returns either cars/1 or voitures/1 depending on the locale

推荐阅读