login event handling in laravel 5

后端 未结 8 2514
温柔的废话
温柔的废话 2020-12-05 11:46

i am trying to hook to the login even in my L5 app to set last login time and IP address. i can make it work with the following:

Event::listen(\'auth.login\'         


        
相关标签:
8条回答
  • 2020-12-05 11:59

    For 5.2 something like this

    in Listeners:

    use Carbon\Carbon;
    use Illuminate\Auth\Events\Login;
    
    class UpdateLastLoginWithIp
    {
        public function handle(Login $event)
        {
            $event->user->last_login_at = Carbon::now();
            $event->user->last_login_ip = Request::getClientIp()
            $event->user->save();
        }
    }
    

    In EventServiceProvider.php :

    protected $listen = [
            'Illuminate\Auth\Events\Login' => [
                'City\Listeners\UpdateLastLoginWithIp',
            ],
        ];
    
    0 讨论(0)
  • 2020-12-05 12:05

    EDIT: this only works in 5.0.* and 5.1.*.

    For the 5.2.* solution see JuLiAnc response below.

    after working with both proposed answers, and some more research i finally figured out how to do this the way i was trying at first.

    i ran the following artisan command

    $ php artisan handler:event AuthLoginEventHandler
    

    Then i altered the generated class removing the import of the Event class and and imported the user model. I also passed User $user and $remember to the handle method since when the auth.login event is fired, thats what is passed.

    <?php namespace App\Handlers\Events;
    
    use Illuminate\Queue\InteractsWithQueue;
    use Illuminate\Contracts\Queue\ShouldBeQueued;
    use App\User;
    
    class AuthLoginEventHandler {
    
        /**
         * Create the event handler.
         *
         * @return void
         */
        public function __construct()
        {
            //
        }
    
        /**
         * Handle the event.
         *
         * @param  User $user
         * @param  $remember
         * @return void
         */
        public function handle(User $user, $remember)
        {
            dd("login fired and handled by class with User instance and remember variable");
        }
    
    }
    

    now i opened EventServiceProvided.php and modified the $listen array as follows:

    protected $listen = [
        'auth.login' => [
            'App\Handlers\Events\AuthLoginEventHandler',
        ],
    ];
    

    i realized if this doesn't work at first, you may need to

    $ php artisan clear-compiled
    

    There we go! we can now respond to the user logging in via the auth.login event using an event handler class!

    0 讨论(0)
提交回复
热议问题