在Laravel中为每个请求创建不同的会话

时间:2019-04-04 07:34:56

标签: php laravel session

我遇到了以下问题:每当我向Laravel发出单个请求时,都会使用同一会话,每当我发出多个Ajax请求时,Laravel就会继续创建新会话。

我在API路由上应用了StartSession和EncryptCookies中间件。我的内核的外观如下:

    'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            \App\Http\Middleware\EncryptCookies::class,
            'bindings',
            AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
        ],

任何人都没有一个想法,为什么实际上在实践中应该对已创建的会话更新会话cookie时会创建多个新会话。

2 个答案:

答案 0 :(得分:0)

Http应用程序是无状态的,这意味着您可以手动处理多个请求的会话。

清除所有会话数据

$request->session()->flush();

生成新的会话ID

$request->session()->regenerate();

Latavel不是期望的框架

答案 1 :(得分:0)

AddQueuedCookiesToResponse::class

应该是:

\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class

这是我的内核中间件组供参考

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        \App\Http\Middleware\EncryptCookies::class,
        'bindings',
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
    ],
];