Laravel 5路由前缀 [英] Laravel 5 route prefix

查看:100
本文介绍了Laravel 5路由前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想指定一个国家/地区为前缀的路线.像这样:

I would like to have a route prefixed by a country. Like this:

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

我的想法是这样做:

<?php

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

这有效.我的问题是我想为每个子路径自动加载Country并能够从控制器和视图中使用它.

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.

有任何提示吗?

推荐答案

我提出的解决方案依赖于特定的中间件.

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']);

    // ...

}

和中间件.

<?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);
    }
}

您可能会猜到,这段代码是针对瑞士应用程序的,因此到处都是_CH.

As you can guess, this code was meant for a swiss application, hence the _CH everywhere.

这篇关于Laravel 5路由前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆