问题描述
我知道有自动插入的字段(例如 updated_at 和 created_at)但我想知道是否有类似 Eloquent 方法 timestamp() 还是 Laravel 产生时间戳的方式?
I know there are fields automatically inserted (e.g. updated_at and created_at) but I was wondering if there is like an Eloquent method timestamp() or the Laravel way to produce timestamps?
例如,我想在用户每次登录我的系统时记录一个时间戳并将其存储到数据库中,这样我们就可以看到每个用户的上次登录日期和时间详细信息.
For instance, I want to record a timestamp every time a user logs in to my system and store it into the database, so we can see each user's last login date and time details.
推荐答案
您可以观察到 auth.login
事件并更新用户的上次登录时间.请参阅 文档 中的第一个示例,了解事件以准确完成您想要做的事情.
You may observe the auth.login
event and update the user's last login time. See the first example in the documentation for events to accomplish exactly what you're trying to do.
Event::listen('auth.login', function($user) {
$user->last_login = new DateTime;
$user->save();
});
注意:在 4.0 中,事件名称为 user.login
.在 4.1 中,事件名称为 auth.login
Note: In 4.0, the event name is user.login
. In 4.1, the event name is auth.login
事件监听器的放置位置完全取决于您.如果您阅读链接到文档页面,它会指出:
It's really up to you where you put your Event listeners. If you read the linked to doc page, it states:
所以,您知道如何注册事件,但您可能想知道在哪里注册注册他们.别担心,这是一个常见的问题.很遗憾,这是一个很难回答的问题,因为您可以注册一个活动几乎在任何地方!但是,这里有一些提示.再次,像大多数其他人一样引导代码,您可以在其中一个启动文件中注册事件比如app/start/global.php.
So, you know how to register events, but you may be wondering where to register them. Don't worry, this is a common question. Unfortunately, it's a hard question to answer because you can register an event almost anywhere! But, here are some tips. Again, like most other bootstrapping code, you may register events in one of your start files such as app/start/global.php.
如果您的启动文件过于拥挤,您可以创建一个从开始文件中包含的单独的 app/events.php 文件.这是一个简单的解决方案,可以让您的活动注册保持干净与您的其他引导程序分开.如果你喜欢上课基于方法,您可以在服务提供商中注册您的活动.由于这些方法都不是本质上正确"的,因此选择一个根据您的大小,您感觉舒适的方法应用.
If your start files are getting too crowded, you could create a separate app/events.php file that is included from a start file. This is a simple solution that keeps your event registration cleanly separated from the rest of your bootstrapping. If you prefer a class based approach, you may register your events in a service provider. Since none of these approaches is inherently "correct", choose an approach you feel comfortable with based on the size of your application.
我个人的偏好是在服务提供商中注册它们,因为这会使它们保持隔离,对我来说是更Laravel"的做事方式.如果您需要服务提供商的帮助,请参阅此文档条目.
My personal preference would be to register them within a Service Provider, since that would keep them segregated and to me is the more 'Laravel' way of doing things. If you need help with service providers, see this documentation entry.
但是,如果您真的只是想尽快启动并运行某些东西,那么在 app/start/global.php
However, if you really just want to get something up and running as quickly as possible, it would be just as easy for you to register that listener inside of app/start/global.php
这篇关于Laravel - 上次登录日期和时间时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!