How to send the password reset link via email using queue in laravel 5

后端 未结 3 986
没有蜡笔的小新
没有蜡笔的小新 2020-12-16 14:15

I am using the ResetsPasswords trait by laravel to implement password reset. What I would like to achieve is to send the email using queue. Digging through the code I found

3条回答
  •  猫巷女王i
    2020-12-16 14:47

    This is where the Laravel container comes to the rescue. If you don't like the functionality of a core component then you can go ahead and override it fairly painlessly.

    First things first you will need to create your own PasswordBroker:

    namespace App\Auth\Passwords;
    
    use Illuminate\Auth\Passwords\PasswordBroker as IlluminatePasswordBroker;
    
    class PasswordBroker extends IlluminatePasswordBroker
    {
    
        public function emailResetLink()
        {
            $view = $this->emailView;
    
            return $this->mailer->queue($view, compact('token', 'user'), function ($m) use ($user, $token, $callback) {
                $m->to($user->getEmailForPasswordReset());
                if (! is_null($callback)) {
                    call_user_func($callback, $m, $user, $token);
                }
            });
        }
    
    }
    

    Change your namespace to whatever you want if you want to place it elsewhere in your app.

    Since the service provider registering the service is a deferred service provider you will need to create your own provider to replace it. Probably the easiest way to do this is extend Illuminate\Auth\Passwords\PasswordResetServiceProvider with something like the following:

    namespace App\Providers;
    
    use App\Auth\Passwords\PasswordBroker;
    
    class PasswordResetServiceProvider extends \Illuminate\Auth\Passwords\PasswordResetServiceProvider
    {
    
        protected function registerPasswordBroker()
        {
            $this->app->singleton('auth.password', function ($app) {
                $tokens = $app['auth.password.tokens'];
    
                $users = $app['auth']->driver()->getProvider();
    
                $view = $app['config']['auth.password.email'];
    
                return new PasswordBroker(
                    $tokens, $users, $app['mailer'], $view
                );
            });
        }
    
    }
    

    Finally in your config/app.php file remove Illuminate\Auth\Passwords\PasswordResetServiceProvider::class and add App\Providers\PasswordResetServiceProvider::class to your 'providers' array.

    Laravel will now use your implementation of the PasswordBroker rather than the stock framework one and you don't have to worry about modifying framework code.

提交回复
热议问题