Laravel Auth count user login

非 Y 不嫁゛ 提交于 2020-01-14 06:18:05

问题


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.


回答1:


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);
        }
    }
    



回答2:


You would need to create a new field into your users table. After this take a look and override the postLogin function in your controller. More information about this function can be found here Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers.



来源:https://stackoverflow.com/questions/36767556/laravel-auth-count-user-login

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!