phantomphoenix phantomphoenix - 7 months ago 60
PHP Question

Fire an event when the user logins in 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?

Answer

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.