最近我从Laravel 5.3
升级到Laravel 5.2
,之后我发现我为设置用户语言而创建的Localization
中间件已停止工作,不知道为什么?
我使用基于token
的{{1}}。
中间件如下:
authentication
我的<?php namespace App\Http\Middleware;
use Closure;
use PhpSpec\Exception\Exception;
use Illuminate\Support\Facades\Auth;
class Localization {
public function handle($request, Closure $next, $guard = null)
{
if(!Auth::guard()->guest())
{
if(!session('current_locale')) {
$localecode = Auth::guard($guard)->user()->getLocale();
session('current_locale',empty ($localecode) ? 'en' : $localecode);
\App::setLocale($localecode);
}else{
\App::setLocale(session('current_locale'));
}
}
return $next($request);
}
}
如下:
routes/api.php
Route::group(['prefix' => 'api/service/v1', 'middleware' => ['api'], 'guard' => 'api'], function(){
Route::get("someUrlHere","SomeControler@SomeMethod");
Route::group(['middleware' => ['auth:api','localization','beforeMiddleware', 'afterApiCallMiddleware'], 'guard' => 'api'], function() {
Route::get("SomeOtherUrlHere","SomeOtherControler@SomeOtherMethod");
});
});
如下:
config/auth.php
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
];
如下:
app/Http/Kernal.php
每次调用方法时,我发现<?php namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel {
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
'Barryvdh\Cors\HandleCors',
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
protected $routeMiddleware = [
'auth' => 'App\Http\Middleware\Authenticate',
'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'localization'=>'App\Http\Middleware\Localization',
'afterMiddleware' => 'App\Http\Middleware\AfterMiddleware',
'beforeMiddleware' => 'App\Http\Middleware\BeforeMiddleware',
'afterApiCallMiddleware' => 'App\Http\Middleware\AfterApiCall',
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
];
}
在$guard
中间件的handle()
方法中为Localization
。
答案 0 :(得分:2)
因为$guard
是中间件中的附加参数,所以您必须手动传递它。您应该可以通过以下方式更改Route :: group中间件数组中的值:
'localization'
为:
'localization:api'
希望这有帮助!