skip to Main Content

I need to get an accurate timestamp of the request in order to then calculate the session end time

I need the timestamp in the layout to be available globally for some JS script, so right now I store it in the layout file:

// layout.blade.php

<div id="request-timestamp" data-request-timestamp="{{ now()->timestamp }}"></div>

Then I can access it using JS:

const requestTimestamp = document.getElementById("request-timestamp").dataset.requestTimestamp;

But, is there a way to get a more accurate timestamp to the time where Laravel actually saves the session time? Because in my app, there are a few DB connections before it actually gets to the frontend, so it might be less accurate.

Can I somehow send the request timestamp to the layout file in a more accurate way?

2

Answers


  1. Chosen as BEST ANSWER

    I ended up using the LARAVEL_START constant that is defined in the public/index.php file, which returns the unix timestamp:

    // public/index.php
    
    define('LARAVEL_START', microtime(true));
    

    And then set it in a div:

     <div id="request-timestamp" data-request-timestamp="{{ LARAVEL_START }}"></div>
    

    That works pretty well.


  2. To ensure that the timestamp is as close as possible to the server-side request processing, you can get it in the controller and pass it directly to the view.

    Controller

    public function index()
    {
        $requestTimestamp = now()->timestamp;
        
        return view('your_view', compact('requestTimestamp'));
    }
    

    Script

    <script>
        const requestTimestamp = {{ $requestTimestamp }};
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search