简体   繁体   English

会话不适用于中间件Laravel 5

[英]Session not working in middleware Laravel 5

Im trying to work with Sessions in Laravel 5 Middleware, but they are not working. 我试图在Laravel 5 Middleware中使用Sessions,但它们无法正常工作。 To be specific - var_dump(Session::all()); 具体而言 - var_dump(Session::all()); at the start of handle method gives me array with one value - _tokken, then at the end of this method 在handle方法的开头给我一个数组--_tokken,然后在这个方法的最后

Session::put('lang',$locale);
var_dump(Session::all());

Gives me array with two values, _tokken and my lang key, but after refresh its the same, as I understand there should be same result after second refresh. 给我数组有两个值,_tokken和我的lang键,但刷新后它相同,据我所知,第二次刷新后应该有相同的结果。

I though maybe I have my middleware loaded before Session middleware, which was true, then I switched and now my Kernel.php looks like this - 我可能在Session中间件之前加载了我的中间件,这是真的,然后我切换了,现在我的Kernel.php看起来像这样 -

protected $middleware = [
        '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',
        'App\Http\Middleware\Language',

    ];

So I ask - what am I doing wrong? 所以我问 - 我做错了什么?

Edit: Digging in Illuminate\\Session\\Middleware\\StartSession I found this - 编辑:挖掘Illuminate \\ Session \\ Middleware \\ StartSession我发现了这个 -

//Note that the Laravel sessions do not make use of PHP "native" sessions in any way since they are crappy.

as a comment, so my testing with session_status() is not relavent. 作为评论,所以我对session_status()的测试不是相关的。

You need to use 你需要使用

\Session::save();

Whenever you want to save the modification so lets say I want to store the language of the user 每当你想保存修改时,我就说我想存储用户的语言

\Session::put('lang','en');
\Session::save();

When you refresh now you will find your newly created key. 现在刷新时,您将找到新创建的密钥。

I had the same problem, I was using Sessions to store the locale at login, then redirect to the main dashboard, but when the middleware loads, the session is not initiated yet. 我遇到了同样的问题,我使用Sessions在登录时存储区域设置,然后重定向到主仪表板,但是当中间件加载时,会话尚未启动。 So it wouldn't work. 所以它不会起作用。

Let me say first, I'm no Laravel expert, but this way works in Laravel 5.3: 首先我要说的是,我不是Laravel专家,但这种方式适用于Laravel 5.3:

1) php artisan make:middleware SetApplicationLanguage 1)php artisan make:中间件SetApplicationLanguage

2) Add this to app/Http/Kernel.php $middlewareGroup variable: 2)将其添加到app / Http / Kernel.php $ middlewareGroup变量:

\Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\SetApplicationLanguage::class,

Notice that this new Middleware comes AFTER the StartSession class. 请注意,这个新的中间件在StartSession类之后出现。

3) This is my app/Http/MiddleWare/SetApplicationLanguage.php: 3)这是我的app / Http / MiddleWare / SetApplicationLanguage.php:

namespace App\Http\Middleware;

use App;
use Closure;
use Illuminate\Support\Facades\Auth;

class SetApplicationLanguage
{

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request            
     * @param \Closure $next            
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (isset(Auth::user()->locale)) {
            App::setLocale(Auth::user()->locale);
        }

        return $next($request);
    }
}

Notice that I don't use Session in it this example. 请注意,我在这个例子中没有使用Session。 That's because when I add my Middleware AFTER the StartSession class, session would work, but Auth::user() would be available again, so I could just use Auth::user()->locale and no need for Sessions at all. 那是因为当我在StartSession类之后添加我的中间件时,会话会起作用,但是Auth :: user()会再次可用,所以我可以使用Auth :: user() - > locale,根本不需要Sessions。

But you could do it, just use App::setLocale(Session::get('locale')) instead and of cause include the Session facade. 但你可以这样做,只需使用App :: setLocale(Session :: get('locale'))而不是原因包括Session facade。

I had the same problem. 我有同样的问题。 @WoodyDRN said you need add StartSession middleware to your kernel file to you but it is not best way to solve this problem. @WoodyDRN表示您需要将StartSession中间件添加到您的内核文件中,但这不是解决此问题的最佳方法。 So, how do I know that? 那么,我怎么知道呢? Because I added and request the validation system is broken. 因为我添加并请求验证系统坏了。

Best way to solve this problem, adding your language middleware to web middleware array 解决此问题的最佳方法是将语言中间件添加到Web中间件阵列

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

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

If you need the session in your current middleware I found a(n) (ugly) workaround. 如果您需要在当前中间件中进行会话,我发现了(n)(丑陋)解决方法。

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Session\Middleware\StartSession;

class MiddlewareThatNeedsTheSession
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
     public function handle($request, Closure $next)
     {
        return app(StartSession::class)->handle($request, function ($request) use ($next) {

            /** @var Response $response */
            $response = $next($request);

            // do something with session
            session(['foo' => 'bar']);

            return $response;
        });
    }
}

另外需要注意的是,如果你正在制作一些操作/从会话中检索数据的中间件,你需要确保它在StartSession Web中间件之后加载。

I had same problem, I was setting value in Middleware and unsetting in same place if some condition is true. 我遇到了同样的问题,如果某些条件成立,我在中间件中设置值并在同一个地方取消设置。

I totally forgot about 404s, some files was getting 404 (missing images) so nginx was passing request to Laravel app to show 404 page, and because it was other url I was unsetting there. 我完全忘了404s,有些文件得到404(缺少图像)所以nginx将请求传递给Laravel应用程序显示404页面,因为它是其他网址我在那里取消了。 I think its the same issue with storing language stuff in session. 我认为在会话中存储语言内容存在同样的问题。 Just check your browser networking and see what requests are being made while loading the page, you might be setting and unsetting at the same time 只需检查您的浏览器网络并查看加载页面时正在进行的请求,您可能同时设置和取消设置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM