Laravel 5.0.*中间件,用于在处理路由之前从url中删除前缀区域设置

Ben*_*Ben 5 middleware routes laravel

我正在寻找一种方法,使所有应用程序路由具有多个语言环境,而无需使用路由组.这是因为我使用外部扩展包,这意味着路由在很多地方注册.

基本上我想要/ foo/bar以及/ en/foo/bar,/ de/foor/bar,/ es/foo/bar等都可以通过/ foot/bar路由识别和处理

 Route::get('foo/bar', function () {
     return App::getLocale() . ' result';
 });
Run Code Online (Sandbox Code Playgroud)

所以上面会给我'结果'或'结果'或'结果'.

我已经有了基于路径段设置语言环境的中间件.我试过以下没有运气.

   ...
   $newPath =  str_replace($locale,'',$request->path());

   $request->server->set('REQUEST_URI',$new_path);

 }

 return $next($request);
Run Code Online (Sandbox Code Playgroud)

希望这是可能的,或者还有其他方法可以实现它.

编辑 - - -

基于下面的评论,我通过将以下代码添加到public/index.php中来快速攻击它.希望通过编辑请求对象可以更好地了解我想要实现的目标.

$application_url_segments = explode( '/', trim( $_SERVER["REQUEST_URI"], '/' ) );

$application_locale = $application_url_segments[0];

$application_locales = ['en' => 'English', 'de' => 'German'];

if ( array_key_exists( $application_locale, $application_locales ) ) {

    $_SERVER["REQUEST_URI"] = str_replace( '/' . $application_locale,'',$_SERVER["REQUEST_URI"] );

}
Run Code Online (Sandbox Code Playgroud)

Pas*_*nes 1

您可以通过提前连接到应用程序来轻松实现此目的。创建一个 ServiceProvider 并创建一个register方法并将您的逻辑放入其中。

<?php namespace App\Providers;

use Illuminate\Support\ServiceProviders;
use Illuminate\Support\Facades\Request;

class LocaleServiceProvider extends ServiceProvider {

    // Fires during the registration of this ServiceProvider :)
    public function register(Request $request) {

        // Altar the Request object here
        // ...
        // ...

    }
}
Run Code Online (Sandbox Code Playgroud)