当用户登录Laravel时触发事件

I am trying to implement events, where I have to fire an event when the user logs in.

I am following this link - http://laravel.com/docs/5.1/events#event-subscribers, but there is no result when I log in or log out.

public function onUserLogin($event) {
        $user = new User;

        $user->last_login_on = Carbon::now();

        $user->save();
    }

    /**
     * Handle user logout events.
     */
    public function onUserLogout($event) {
        $user = new User;

        $user->last_login_on = Carbon::now();

        $user->save();
    }

And this is the subscribe.

public function subscribe($events)
    {
        $events->listen(
            'App\Events\UserLoggedIn',
            'App\Listeners\UserEventListener@onUserLogin'
        );

        $events->listen(
            'App\Events\UserLoggedOut',
            'App\Listeners\UserEventListener@onUserLogout'
        );
    }

Though, I am not aware of what should I put in here, App\Events\UserLoggedIn

Where can I fire this event?

And how do I implement this functionality using Events?

The events you need to listen on are:

  • auth.login - fired when user logged in successfully
  • auth.logout - fired when user logged out
  • auth.attempt - fired when user attempts to log in

Those are the events that Laravel fires automatically - see Illuminate\Auth\Guard class which is what you get when you use Auth facade.

In order for your listeners to work you need to do:

$events->listen(
    'auth.login',
    'App\Listeners\UserEventListener@onUserLogin'
);

$events->listen(
    'auth.logout',
    'App\Listeners\UserEventListener@onUserLogout'
);

Another option is to define separate handler classes for both events, e.g.:

class UserEventLoginHandler {
  public function handle($event) {
    //do some logic here
  }
}

class UserEventLogoutHandler {
  public function handle($event) {
    //do some logic here
  }
}

and then define listeners in :

protected $listen = array(
  'auth.login' => 'App\Listeners\UserEventLoginListener',
  'auth.logout' => 'App\Listeners\UserEventLogoutListener'
);

You can also use Laravel's command to generate the handlers - see https://mattstauffer.co/blog/laravel-5.0-events-and-handlers for more details.

I know this question is quite old but to answer the last comment in case someone else is struggling with the same issue. You also need to access the currently logged in user in your onUserLogin and onUserLogout methods since creating a new instance of the user model creates a new user rather than updating the currently logged in user.