Case
Using Middleware, Session & Carbon to check if the session/shopping cart is created longer than 20 minutes ago so the session can be flushed. (Routes are grouped inside the middleware)
Current data is being run on Homestead, but same problems occur on my live website which is being run on a Digital Ocean server
class CheckCart
{
public function handle($request, Closure $next)
{
// Defining current timestamp
$now = Carbon::now();
// created_at from the session
$created_at = $request->session()->get('created_at');
// If the cart count is == 1, & created_at is null -> put created at date in session
if (Cart::count() == 1 && $created_at == null) {
$request->session()->put('created_at', $now);
}
// If created at date + 20 minutes is earlier than current time, flush (empty) session
if ($created_at != null) {
if ($created_at->addMinutes(20) < $now) {
$request->session()->flush();
}
}
return $next($request);
}
}
Problem
Local timefrom my Macbook is2017-01-06 00:00Carbon::now()is2017-01-05 23:25created_attimestamp is (which was eventually set byCarbon::now()) is2017-01-06 03:20
How can these timestamps differ so much, and especially, how can created_at which defined by Carbon::now() at some point be at least 7 hours later?
- All timezones are
Europe/Amsterdam

The problem is with
$created_at->addMinutes(20). Everytime your code gets executed (with refresh, a request or something else) it adds 20 minutes to the session value. Then there's also the problem as mentioned in the comments about Homestead's time being different than your actual machine.To solve the
created_atproblem, you should instead make a copy of it by doing$created_at->copy()->addMinutes(20). Apply this trick with all your other code where actually a copy is needed instead of the object itself. Hope that helps!