Laravel 中的主路由页面
Master routing page in Laravel
以前我创建了自己的 MVC,并且有一个 index.php
所有页面都从它的方式传递。我的意思是,我可以将重定向 (header('Location: ..');
) 放入 index.php
,然后 none 我的网站页面无法打开。
现在我使用 Laravel 并且我需要一个核心页面(比如 index.php
)。因为我的新网站支持多国语言。这是我当前的代码:
// app/Http/routes.php
Route::get('/{locale?}', 'HomeController@index');
// app/Http/Controllers/HomeController.php
public function index($locale = null)
{
if(!is_null($locale)) {
Lang::setLocale($locale);
}
dd(Lang::getLocale());
/* http://localhost:8000 => output: en -- default
* http://localhost:8000/abcde => output: en -- fallback language
* http://localhost:8000/en => output: en -- defined language
* http://localhost:8000/es => output: es -- defined language
* http://localhost:8000/fa => output: fa -- defined language
*/
}
如您所见,在我目前的算法中,我需要检查用户为每条路线设置的语言。我的网站也有近 30 条路线。我可以为每条路线手动执行 30 次,但我认为有一种方法可以让我为所有路线执行一次。没有吗?
换句话说,如何为每个页面设置当前语言(用户已设置)?我应该 check/set 分别为每条路线吗?
Laravel中有更聪明的方法可以解决您的问题。它被称为Middleware。所以你可以创建 LangMiddleware 并将你的逻辑放在里面。
类似
public function handle($request, Closure $next, $locale = null)
{
if ($locale && in_array($locale, config('app.allowed_locales'))) {
Lang::setLocale($locale);
}
else{
Lang::setLocale(config('app.fallback_locale'));
}
return $next($request);
}
以前我创建了自己的 MVC,并且有一个 index.php
所有页面都从它的方式传递。我的意思是,我可以将重定向 (header('Location: ..');
) 放入 index.php
,然后 none 我的网站页面无法打开。
现在我使用 Laravel 并且我需要一个核心页面(比如 index.php
)。因为我的新网站支持多国语言。这是我当前的代码:
// app/Http/routes.php
Route::get('/{locale?}', 'HomeController@index');
// app/Http/Controllers/HomeController.php
public function index($locale = null)
{
if(!is_null($locale)) {
Lang::setLocale($locale);
}
dd(Lang::getLocale());
/* http://localhost:8000 => output: en -- default
* http://localhost:8000/abcde => output: en -- fallback language
* http://localhost:8000/en => output: en -- defined language
* http://localhost:8000/es => output: es -- defined language
* http://localhost:8000/fa => output: fa -- defined language
*/
}
如您所见,在我目前的算法中,我需要检查用户为每条路线设置的语言。我的网站也有近 30 条路线。我可以为每条路线手动执行 30 次,但我认为有一种方法可以让我为所有路线执行一次。没有吗?
换句话说,如何为每个页面设置当前语言(用户已设置)?我应该 check/set 分别为每条路线吗?
Laravel中有更聪明的方法可以解决您的问题。它被称为Middleware。所以你可以创建 LangMiddleware 并将你的逻辑放在里面。
类似
public function handle($request, Closure $next, $locale = null)
{
if ($locale && in_array($locale, config('app.allowed_locales'))) {
Lang::setLocale($locale);
}
else{
Lang::setLocale(config('app.fallback_locale'));
}
return $next($request);
}