简体   繁体   English

Laravel 5路由前缀

[英]Laravel 5 route prefix

I would like to have a route prefixed by a country. 我想要一条以国家为前缀的路线。 Like this: 像这样:

/us/shop
/ca/shop
/fr/shop

My idea was to do so: 我的想法是这样做:

<?php

Route::group([
    'prefix' => '{country}'
], function() {
    Route::get('shop', 'ShopController@Index');
    // ...
});

This works. 这可行。 My problem is that I'd like to autoload the Country for each sub route and be able to use it from the controller as well as the view. 我的问题是我想为每个子路线自动加载Country ,并能够从控制器和视图中使用它。

Any hints? 有什么提示吗?

The solution, I've came up with relies on a specific middleware. 我提出的解决方案依赖于特定的中间件。

<?php

Route::get('', function() {
    return redirect()->route('index', ['language' => App::getLocale()]);
});

Route::group([
    'prefix' => '{lang}',
    'where' => ['lang' => '(fr|de|en)'],
    'middleware' => 'locale'
], function() {

    Route::get('', ['as' => 'index', 'uses' => 'HomeController@getIndex']);

    // ...

}

and the middleware. 和中间件。

<?php

namespace App\Http\Middleware;

use App;
use Closure;
use View;

class Localization {
    public function handle($request, Closure $next) {
        $language = $request->route()->parameter('lang');

        App::setLocale($language);

        // Not super necessary unless you really want to use
        // number_format or even money_format.
        if ($language == "en") {
            setLocale(LC_ALL, "en_US.UTF-8");
        } else {
            setLocale(LC_ALL, $language."_CH.UTF-8");
        }

        View::share('lang', $language);

        return $next($request);
    }
}

As you can guess, this code was meant for a swiss application, hence the _CH everywhere. 如您所料,该代码是针对瑞士应用程序的,因此_CH处处可见。

实现此目的的一种方法是使用Request门面的segment函数:

$country = Request::segment(1);

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

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