英文:
Get the most accurate request time from Laravel to be used in the frontend
问题
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?
英文:
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?
答案1
得分: 2
为确保时间戳尽可能接近服务器端的请求处理,您可以在控制器中获取它并将其直接传递给视图。
控制器
public function index()
{
$requestTimestamp = now()->timestamp;
return view('your_view', compact('requestTimestamp'));
}
脚本
<script>
const requestTimestamp = {{ $requestTimestamp }};
</script>
英文:
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>
答案2
得分: 0
我最终使用了在public/index.php
文件中定义的LARAVEL_START
常量,它返回Unix时间戳:
// public/index.php
define('LARAVEL_START', microtime(true));
然后将它设置在一个div
元素中:
<div id="request-timestamp" data-request-timestamp="{{ LARAVEL_START }}"></div>
这个方法效果还不错。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论