Laravel 5 store user login and logout activity

How to store login logout activity in Laravel

If you have developed an app using the Laravel framework so you must have needed to store the login and logout activity of the user to make your app and user account security. In, this article I am going to tell you how you can store user login/logout activity.

I am supposing that you are familiar with the Laravel framework.

How to achieve this

I am going to use Event service provider to make it simple. You can also use authenticated() method of AuthenticatesUsers trait but then you have to make the changes in the authentication library. So, I don’t think its a good idea, I am not going to use this. Let’s do it.

Store Login Activity

  1. Open the app/Providers/EventServiceProvide.php file and add the following code to $listen variable.
        'Illuminate\Auth\Events\Login' => [
            'App\Listeners\LoginActivity',
        ],
    
  2. Now open Terminal and go to your application folder and run the following command.
    php artisan event:generate
  3. A listeners folder will be created there in the app folder containing the LoginActivity.php file. Change your handle method with the following code:
    public function handle(Login $event)
    {
        $event->user->login_at = date('Y-m-d H:i:s');
        $event->user->save();
    }
  4. Make sure it has the correct namespace.
    use Illuminate\Auth\Events\Login;
    use Illuminate\Queue\InteractsWithQueue;
    use Illuminate\Contracts\Queue\ShouldQueue;

Store Logout Activity

  1. Open the app/Providers/EventServiceProvide.php file and add the following code to $listen variable.
        'Illuminate\Auth\Events\Logout' => [
            'App\Listeners\LogoutActivity',
        ],
    
  2. Now open Terminal and go to your application folder and run the following command.
    php artisan event:generate
  3. A listeners folder will be created there in the app folder containing the LogoutActivity.php file. Change your handle method with the following code:
    public function handle(Logout $event)
    {
        $event->user->logout_at = date('Y-m-d H:i:s');
        $event->user->save();
    }
  4. Make sure it has the correct namespace.
    use Illuminate\Auth\Events\Logout;
    use Illuminate\Queue\InteractsWithQueue;
    use Illuminate\Contracts\Queue\ShouldQueue;

1 Comment

  1. Appreciating the time and effort you put into your blog and detailed information you offer.
    It’s good to come across a blog every once in a while that isn’t the same unwanted rehashed information. Excellent read!

    I’ve bookmarked your site and I’m adding your RSS feeds to
    my Google account.