Laravel - 为每条路线添加路线通配符

Laravel - Add Route Wildcard to every Route

我已经在 laravel 中创建了一个多语言应用程序,并且对于每条路线(因为我想在 url 中看到我的语言是什么)我需要

www.example.com/{locale}/home 

例如,{locale} 是设置的语言,home well 是 home。但对于每条路线,我都需要声明该语言环境通配符。有没有办法用中间件或其他东西来完成这个,在执行路由之前添加这个? 谢谢!

可以使用前缀。

Route::group(['prefix' => '{locale}'], function () {
    Route::get('home','Controller@method');
    Route::get('otherurl','Controller@method');
});

这里是您现在如何访问它。

www.example.com/{locale}/home 
www.example.com/{locale}/otherurl

了解更多信息。 https://laravel.com/docs/5.8/routing#route-group-prefixes

不确定我是否理解你的请求,但我相信这是你正在寻找的范围:

可以接收 "locale" 的通用路由,您可以根据该路由以适当的语言提供页面。

如果是这样的话,我会这样定义一条路线:

Route::get({locale}/home, 'HomeController@index');

然后在您的 HomeController@index 中,您将拥有 $locale 变量,您可以根据该变量实现您的语言逻辑:

class HomeController extends Controller
{
    /**
     * Show the application homepage.
     *
     * @return mixed (View or Redirect)
     */
    public function index(Request $request, $locale)
    {
        switch ($locale) {
        case 'en':
            //do english logic
            break;
        so on...
        }
    }

希望对你有帮助