Laravel使用regexp的可选前缀路由

标签 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',并且肯定没有称为“authors”的语言。

我用laravel 5.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();

关于Laravel使用regexp的可选前缀路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46032537/

相关文章:

php - 在命名空间中定义 Controller 仍然 Class App\Http\Controllers 在 laravel 5.5 中发生错误

laravel - 如何从 HasMany 关系中分离元素?

php - 如何使用 Laravel Passport 为密码授予客户端创建 token ?

php - 如果用户在 php POST 请求期间点击刷新,则回滚 MySQL 事务

php - 如何在 Laravel 5.7 中获取 json 值?

mysql - Laravel 从多对多数据透视表中删除单个数据

laravel - Chrome 将 .dev 重定向到 https

javascript - Laravel 5.5 Invisible Recaptcha 不提交表单

facebook-graph-api - Laravel 5.5 社交名媛不工作

javascript - Laravel-Vue JS : What is the best way access backend