我在中间件中的会话中存储值:

但是当我刷新或转到新页面时,会话为空。
我做错了什么?

class WorkflowContextMiddleware
{
    /**
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $types = $request->input('types', []);

        foreach ($types as $type => $context) {
            $request->session()->put("somekey.contexts.{$type}", $context);
            $request->session()->save();
        }

        return $next($request);
    }
}


路线:

Route::group([
    'prefix' => LaravelLocalisation::setLocale(),
    'middleware' => ['web','localise','localeSessionRedirect']
], function () {
    Route::get('/', function() {
        (new \Illuminate\Support\Debug\Dumper)->dump(\Session::get('somekey'));
    });
});


路线提供者:

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to the controller routes in your routes file.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'Arcanine\Http\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @param  \Illuminate\Routing\Router  $router
     * @return void
     */
    public function boot(Router $router)
    {
        //

        parent::boot($router);
    }

    /**
     * Define the routes for the application.
     *
     * @param  \Illuminate\Routing\Router  $router
     * @return void
     */
    public function map(Router $router)
    {
        $router->group(['namespace' => $this->namespace], function ($router) {
            require app_path('Http/routes.php');
        });
    }
}


内核.php

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,
        \App\Workflow\Http\Middleware\WorkflowContextMiddleware::class,
    ],

最佳答案

为了使您的会话正常进行,请将所有路由包装在以下范围内:

Route::group(['middleware' => 'web'], function () {
    ...
});

关于laravel - 中间件中的 session 不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41160488/

10-10 23:08