简体   繁体   English

Laravel 5 Route Filter正则表达式

[英]Laravel 5 Route filter regex

I'm trying to implement a laravel website that supports two languages (pt and en with pt fallback already implemented). 我正在尝试实现一个支持两种语言的laravel网站(已实现pt和en并带有pt后备功能)。 The desired url's should be www.example.com/pt/list for portuguese and www.example.com/en/list for english. 所需的网址应该是www.example.com/pt/list(对于葡萄牙语)和www.example.com/en/list(对于英语)。 When no language is inserted, should work with pt for default. 如果未插入任何语言,则默认情况下应使用pt。 I have the following code: [routes.php] 我有以下代码:[routes.php]

Route::filter('localization', function() {
    App::setLocale(Route::input('lang'));
});
Route::group(['prefix' => '{lang?}', 'before' => 'localization'], function() {
    Route::get('/', 'HomeController@index');
    Route::get('/list','ListController@index');
});

When language is defined all works well, but otherwise it will always redirect to the homepage even when there is no router to this URL. 定义语言后,所有方法都可以正常工作,否则,即使没有指向该URL的路由器,它也将始终重定向到主页。 How can I avoid this behaviour? 我如何避免这种行为? Is it possible to do a regex on a group? 是否可以对组进行正则表达式? Guess the Jason Lewis' Enhanced Router only works in Laravel 4 猜猜杰森·刘易斯的增强型路由器仅适用于Laravel 4

EDIT 1: I could fix it using redirects in htaccess (if no language prefix, then redirect using /pt/ prefix but there must be another way I guess) 编辑1:我可以使用htaccess中的重定向来解决它(如果没有语言前缀,则可以使用/ pt /前缀进行重定向,但是我猜必须有另一种方式)

EDIT 2: Can fix it using the following piece of code but it also involves using redirects, which I guess it could be prevented and the url will always have the language parameter 编辑2:可以使用下面的代码修复它,但它也涉及使用重定向,我想可以避免这种情况,并且url始终具有language参数

Route::filter('localization', function() {
    $accepted_language = array("pt","en");

    $first_segment = Route::input("lang");
    if(in_array($first_segment,$accepted_language))
    {
        /*ALL GOOD, Language in URL*/
        App::setLocale(Route::input('lang'));
    }
    else
    {
        /*REDIRECT WITH LANGUAGE*/
        $segments   = Request::segments();
        $imploded   = implode("/",$segments);
        $url        = "/pt/".$imploded;
        return Redirect::to($url, 301);
    }

});

In my recent project I had the same problem. 在我最近的项目中,我遇到了同样的问题。 You can do it like this: 您可以这样做:

$languages = array('en', 'pt');
$locale = Request::segment(1);

if (in_array($locale, $languages))
{
    App::setLocale($locale);
}
else
{
    redirect('pt')->send();
}

Route::group(['prefix' => $locale], function()
{
    Route::get('/', 'HomeController@index');
    Route::get('list','ListController@index');
});

Or move locales check into the separate middleware. 或将语言环境检查移到单独的中间件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM