Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Carbon date time differs

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 time from my Macbook is 2017-01-06 00:00
  • Carbon::now() is 2017-01-05 23:25
  • created_at timestamp is (which was eventually set by Carbon::now()) is 2017-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

image with code & timestamps

like image 891
Leguam Avatar asked Aug 22 '26 08:08

Leguam


1 Answers

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_at problem, 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!

like image 188
Markinson Avatar answered Aug 24 '26 20:08

Markinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!