我正在尝试在我的 Laravel 5 项目中实现本地化,但遇到了问题。我为了捕捉语言而放入的中间件如下:
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Routing\Redirector;
use Illuminate\Http\Request;
use Illuminate\Foundation\Application;
use Illuminate\Contracts\Routing\Middleware;
class Language implements Middleware {
public function __construct(Application $app, Redirector $redirector, Request $request) {
$this->app = $app;
$this->redirector = $redirector;
$this->request = $request;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Make sure current locale exists.
$locale = $request->segment(1);
if ( ! array_key_exists($locale, $this->app->config->get('app.locales'))) {
$segments = $request->segments();
$segments[0] = $this->app->config->get('app.fallback_locale');
return $this->redirector->to(implode('/', $segments));
}
$this->app->setLocale($locale);
return $next($request);
}
}
内核.php:
protected $middleware = [
'App\Http\Middleware\Language',
'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
'Illuminate\Cookie\Middleware\EncryptCookies',
'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
'Illuminate\Session\Middleware\StartSession',
'Illuminate\View\Middleware\ShareErrorsFromSession',
'App\Http\Middleware\VerifyCsrfToken',
];
routeserviceprovider.php:
public function map(Router $router, Request $request)
{
$locale = $request->segment(1);
$this->app->setLocale($locale);
$router->group(['namespace' => $this->namespace, 'prefix' => $locale], function($router) {
require app_path('Http/routes.php');
});
}
它工作得很好,除了一件事。当我尝试访问http://0.0.0.0/public/css/images/myimage.png时,它会被替换public
为en
,如果我访问/en/public
它会告诉我该路线不存在。
任何帮助将公共目录排除在此之外或以不涉及中间件的更好方式实施本地化?