Search code examples
phplaravelverificationautoblogged

Automatic login after clicking on the link with the token (jrean/laravel-user-verification)


I use the "jrean/laravel-user-verification" package. When I click on the link with the token I want to redirect in my homepage and be already logged. How can I implement this? Thank you)

Laravel: 5.4 Package Version: 4.1


Solution

  • Solve this problem. Add to my register function (RegisterController) event:

    public function register(VerificationRequest $request)
     {
           ...
           event(new Registered($user));
           ...
     }
    

    Сreate listener:

    <?php
    
    namespace App\Listeners;
    
    use Illuminate\Auth\AuthManager;
    use Jrean\UserVerification\Events\UserVerified;
    
    /**
     * Class UserVerifiedListener
     * @package App\Listeners
     */
    class UserVerifiedListener
    {
        /**
         * @var AuthManager
         */
        private $auth;
    
        /**
         * Create the event listener.
         *
         * @param AuthManager $auth
         */
        public function __construct(AuthManager $auth)
        {
            $this->auth = $auth;
        }
    
        /**
         * Handle the event.
         *
         * @param  UserVerified  $event
         * @return void
         */
        public function handle(UserVerified $event)
        {
            $this->auth->guard()->login($event->user);
        }
    }
    

    And register it in :

    app/Providers/EventServiceProvider.php
    <?php
    
    namespace App\Providers;
    
    use App\Listeners\UserVerifiedListener;
    use Illuminate\Support\Facades\Event;
    use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
    use Jrean\UserVerification\Events\UserVerified;
    
    class EventServiceProvider extends ServiceProvider
    {
        /**
         * The event listener mappings for the application.
         *
         * @var array
         */
        protected $listen = [
            UserVerified::class => [
                UserVerifiedListener::class
            ],
        ];
    
        /**
         * Register any events for your application.
         *
         * @return void
         */
        public function boot()
        {
            parent::boot();
    
            //
        }
    
        public function register()
        {
            $this->app->bind(UserVerifiedListener::class, function () {
                return new UserVerifiedListener(
                    $this->app->make('auth')
                );
            });
        }
    }