具有正则表达式的Laravel可选前缀路由

时间:2017-09-04 07:50:23

标签: laravel laravel-5.5

有没有办法创建带前缀的路线,所以我可以有这样的路线

/articles.html -> goes to listing  Controller in default language
/en/articles.html -> goes to the same controller
/fr/articles.html -> goes to the same controller

我目前的问题在于:

Route::group(['prefix=>'/{$lang?}/',function(){});

这样的路线:/authors/author-100.html将匹配前缀'authors`,并且肯定没有称为“作者”的语言。

我使用laravel 5.5

4 个答案:

答案 0 :(得分:6)

使用可选路由参数上的正则表达式匹配时,这应该足够了:

Route::get('/{lang?}, 'SameController@doMagic')->where('lang', 'en|fr');

您也可以在路由组上执行相同的操作,否则in this answer的所有选项显然都有效。

显示使用前缀的更新:

Route::group(['prefix' => '{lang?}', 'where' => ['lang' => 'en|fr']],function (){
    Route::get('', 'SameController@doNinja');
});

就我而言,即使没有lang也没有lang,这应该足够了,也许这个群体可能会在其他路线之前来到。

答案 1 :(得分:5)

似乎没有任何好的方法可以将可选前缀作为组前缀方法使用"可选"正则表达式标记不起作用。但是,可以使用所有路由声明Closure并使用前缀添加一次,而不使用:

$optionalLanguageRoutes = function() {
    // add routes here
}

// Add routes with lang-prefix
Route::group(
    ['prefix' => '/{lang}/', 'where' => ['lang' => 'fr|en']],
    $optionalLanguageRoutes
);

// Add routes without prefix
$optionalLanguageRoutes();

答案 2 :(得分:1)

您可以使用表格来定义接受的语言,然后:

class X(models.Model):
    def save(self, *args, **kwargs):
        pre_obj = X.objects.filter(pk=self.pk).first()
        super(X, self).save(*args, **kwargs)
        # no exception from save
        if pre_obj and pre_obj.state_id != VOID and self.state_id == VOID:
            # send mail

答案 3 :(得分:0)

另一种可行的解决方案是创建一个lang数组并在其上循环:

$langs = ['en', 'fr', ''];

foreach($langs as $lang) {
  Route::get($lang . "/articles", "SomeController@someMethod");
}

请确保这会使您的路线文件可读性降低,但是您可以使用php artisan route:list清楚列出您的路线。

相关问题