簡體   English   中英

會話不適用於中間件laravel 5.2

[英]session is not working in middleware laravel 5.2

我正在嘗試創建一個中間件,計算用戶在一段時間內訪問我的網站的次數。 我嘗試在我的中間件中使用laravel會話。 這是我的代碼:

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'));
}
}

在我的app \\ Http \\ kernel.php中我在SessionStart中間件之后添加了中間件:

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

但每次刷新頁面時,我得到的響應是1.這意味着沒有設置會話。

如何在laravel中間件中使用會話?

[編輯]

我發現問題出在EncryptCookie中間件上。 我的會話驅動程序是數據庫,每次刷新頁面時,會話表中都會添加一條記錄。

當我關閉EncryptCookie中間件時問題得到解決。

你有錯誤的“IF”條件。 您每次都將計數設置為1。 如果是第一次訪問,則設置為“count + 1”(因此它也是1)。 這就是你在做的事情:

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

您的代碼中似乎存在一個小的邏輯問題,我會這樣做

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