问题
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:
Create the
UserEventListenerclass inapp\Listenersnamespace 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' ); } }Subscribe the
UserEventListenerto theEventServiceProvidernamespace 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