How to record login and logout user actions in Laravel

Categorized as Laravel Tagged ,

If you need to audit sign in and sign out events for some security concerns, then you can utilize Laravel auth events, which allow you to easily listen for them.

// Within some applications (especially sensitive ones), it can be useful 
// to record login requests for auditing purposes. While you can attempt to dothis manually,
// a much better approach is to listen for the login and logout events,
// then run any required code within the listener's handle method:

class EventServiceProvider 
{
  protected $listen = [
    'Illuminate\Auth\Events\Login' => ['App\Listeners\LoginListener'],
    'Illuminate\Auth\Events\Logout' => ['App\Listeners\LogoutListener'],
  ];
}

class LoginListener
{
  public function handle(Login $event)
  {
    Log::info("User #{$event->user->id} signed in");    
  }
}

class LogoutListener
{
  public function handle(Logout $event)
  {
    Log::info("User #{$event->user->id} signed out");    
  }
}

Leave a reply

Your email address will not be published. Required fields are marked *