Kji Kji - 6 months ago 116
PHP Question

Laravel Auth count user login

I installed Laravel with the Laravel/Auth.

How can i count how often a user logged in his account?

I tried to find the updated_at function to add a increment command to push up the count.

Answer

You can use events to accomplish it. More information about events can be found on Laravel documentation

You should add a new property loginCount to the User model and its correspondent in db. Make sure that on creation the loginCount field has the default value set to 0.

To increment it when user is logging in you can create a listener which listen on auth.login event:

  1. Create the UserEventListener class in app\Listeners

    namespace App\Listeners;
    
    use App\User;
    
    class UserEventListener
    {
        /**
         * Handle user login events.
         * 
         * @param User $user
         * @param bool $remember
         */
        public function onUserLogin(User $user, $remember)
        {
            $user->loginCount++;
            $user->save();
        }
    
        /**
         * Register the listeners for the subscriber.
         *
         * @param  Illuminate\Events\Dispatcher  $events
         */
        public function subscribe($events)
        {
            $events->listen(
                'auth.login',
                'App\Listeners\UserEventListener@onUserLogin'
            );
        }
    }
    
  2. Subscribe the UserEventListener to the EventServiceProvider

    namespace App\Providers;
    
    use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
    use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
    
    class EventServiceProvider extends ServiceProvider
    {
        /**
         * The event listener mappings for the application.
         *
         * @var array
         */
        protected $listen = [
            'App\Events\SomeEvent' => [
                'App\Listeners\EventListener',
            ],
        ];
    
        /**
         * The subscriber classes to register.
         *
         * @var array
         */
        protected $subscribe = [
            'App\Listeners\UserEventListener',
        ];
    
        /**
         * Register any other events for your application.
         *
         * @param  \Illuminate\Contracts\Events\Dispatcher  $events
         * @return void
         */
        public function boot(DispatcherContract $events)
        {
            parent::boot($events);
        }
    }