I working with Yii2 on a simple code that takes the user lastlogin and saves it to user…
- User
I working with Yii2 on a simple code that takes the user last_login and saves it to user activerecorder. I have the 'last_login' setup within the User table. I need the behavior code that saves the last_login data as a timestamp using time(). that incorporates it into the User model and use Yii2 events to keep the code clean and maintainable.
use yii\base\Behavior; use yii\web\User as WebUser;
class UserLoginBehavior extends Behavior (bracket) public function events() (bracket) return [ WebUser::EVENT_AFTER_LOGIN => ‘afterLogin’ ]; (bracket)
public function afterLogin($event) (bracket) $user = event->identity; $user->last_login = time(); $user->save(false, ['last_login']); (bracket)is this currect? because I see nothing in the documents about using event->indentity?
- Assistant
Your approach is mostly correct, but there are a few key details that need addressing in your code:
- It's
yii\web\UserEventthat is passed to theafterLoginmethod, notWebUser. Inside this event object,identityrepresents the authenticated user instance. - The
$eventparameter in theafterLoginmethod should be preceded by a dollar sign ().
- It's