简体   繁体   English

会话不适用于中间件laravel 5.2

[英]session is not working in middleware laravel 5.2

I am trying to create a middleware that counts how many times a user has accessed my site in a period of time. 我正在尝试创建一个中间件,计算用户在一段时间内访问我的网站的次数。 I tried to use laravel session in my middleware. 我尝试在我的中间件中使用laravel会话。 Here is my code: 这是我的代码:

class SessionHandler {
public function handle($request, Closure $next){
    if(!Session::has('count')){
        Session::set('count', 1);
        Session::save();
    }else{
        $numOfVisits = Session::get('count');
        $numOfVisits++;
        Session::set('count', $numOfVisits);
        Session::save();
    }
    dd(Session::get('count'));
}
}

in my app\\Http\\kernel.php I added the middleware after SessionStart middle ware: 在我的app \\ Http \\ kernel.php中我在SessionStart中间件之后添加了中间件:

protected $middleware = [
    ....
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    ....
    \Dideo\Http\Middleware\SessionHandler::class,
];

but every time I refresh the page I get the response is 1. It means that the session is not set. 但每次刷新页面时,我得到的响应是1.这意味着没有设置会话。

How can I work with session in laravel middleware? 如何在laravel中间件中使用会话?

[EDIT] [编辑]

I found that the problem is with EncryptCookie middleware. 我发现问题出在EncryptCookie中间件上。 My session driver is database and every time I refresh the page a record is added in session table. 我的会话驱动程序是数据库,每次刷新页面时,会话表中都会添加一条记录。

When I turn off EncryptCookie middleware the problem is fixed. 当我关闭EncryptCookie中间件时问题得到解决。

You have wrong "IF" condition. 你有错误的“IF”条件。 You are setting count to 1 every time. 您每次都将计数设置为1。 And set to "count + 1" if it's first visit (so it's also 1). 如果是第一次访问,则设置为“count + 1”(因此它也是1)。 That's what you're doing: 这就是你在做的事情:

if (isset($a)) {
   $a = 1; //set $a to 1
} else {
   $a = $a + 1; //set $a to 1 again
}

There seems to be a small logical problem in your code, I would do it this way 您的代码中似乎存在一个小的逻辑问题,我会这样做

public function handle($request, Closure $next){
    $value = 1; //Initially it is 1
    if(Session::has('count')){ //If a previous save has been made take that value
        $value = Session::get('count') + 1; //add
    }// do not need an else block, first call will save value of 1
    Session::set('count', $value); //Set it to 1 (first call) or the incremented value
    Session::save();
    dd(Session::get('count'));
}

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

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