Search code examples
laravelsessioncookiesphp-carbon

Laravel session expiration on Carbon::setTestNow()


I'm using Carbon::setTestNow() for testing purpose on laravel 4.2 project and all the time when I make next refresh after the method call where I used Carbon::setTestNow() system log me out. It happens because session cookie expiration date sets to Carbon::setTestNow() date. How can I override that because it's annoying to make login again all the time. Thanks, hope some one can help me to find some solution.


Solution

  • Just come to the same situation and here's the result:

    The "official way" is to extend the Illuminate\Session\Middleware::addCookieToResponse or ::getCookieLifetime

    But I find it's quite complicated and bloated. Come to a simple solution:

    Check if the provided mock time is from the past, override the session.lifetime if needed, here's the codeblock I added into app/start/global.php

    // Set mock time if requested
    if ( ! empty($_GET['mocktime'])) {
        try {
            $real_time = \Carbon\Carbon::now();
            $mock_time = \Carbon\Carbon::parse($_GET['mocktime']);
    
            \Carbon\Carbon::setTestNow($mock_time);
    
            $diff_min = $real_time->diffInMinutes($mock_time);
            if ($diff_min > 0) {
                // requested mock time is from the pass
                $org_lifetime = Config::get('session.lifetime');
                Config::set('session.lifetime', $diff_min + $org_lifetime);
            }
    
        } catch (Exception $ex){
            Log::warning('Mocktime requested but unable to set: '.$ex->getMessage());
        }
    }
    

    As this answer is coming late, hope it can help someone later.