如何在Laravel 5默认注册后发送邮件?

21

我对Laravel不熟悉,目前正在使用Laravel 5。为了用户注册和登录,我想使用Laravel的默认系统。但是,我需要在此基础上扩展以下两个功能:

  1. 用户注册后将收到一封电子邮件。
  2. 在保存用户注册信息时,我需要在另一个角色表格中添加一个条目(我已经使用Entrust包进行角色管理)。

如何实现这些功能?


请查看services/registrar.php。 - Emeka Mbah
2个回答

34

你可以修改位于 app/services 的 Laravel 5 默认注册器。

<?php namespace App\Services;

    use App\User;
    use Validator;
    use Illuminate\Contracts\Auth\Registrar as RegistrarContract;
    use Mail;

    class Registrar implements RegistrarContract {

        /**
         * Get a validator for an incoming registration request.
         *
         * @param  array  $data
         * @return \Illuminate\Contracts\Validation\Validator
         */
        public function validator(array $data)
        {
            return Validator::make($data, [
                'name' => 'required|max:255',
                'email' => 'required|email|max:255|unique:users',
                'password' => 'required|confirmed|min:6'
            ]);
        }

        /**
         * Create a new user instance after a valid registration.
         *
         * @param  array  $data
         * @return User
         */
        public function create(array $data)
        {
            $user = User::create([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => \Hash::make($data['password']),
                //generates a random string that is 20 characters long
                'verification_code' => str_random(20)
            ]);

//do your role stuffs here

            //send verification mail to user
            //---------------------------------------------------------
            $data['verification_code']  = $user->verification_code;

            Mail::send('emails.welcome', $data, function($message) use ($data)
            {
                $message->from('no-reply@site.com', "Site name");
                $message->subject("Welcome to site name");
                $message->to($data['email']);
            });


            return $user;
        }

    }

resources/emails/welcome.blade.php 内部

Hey {{$name}}, Welcome to our website. <br>
Please click <a href="{!! url('/verify', ['code'=>$verification_code]) !!}"> Here</a> to confirm email

注意:您需要为验证创建路由/控制器


修改这个文件是一个不好的主意吗?如果composer更新Laravel,这个文件会被覆盖吗? - Josh Mountain
4
@Josh Mountain 没有问题。Composer 只会更新位于 vendor 目录下的 Laravel Framework。 - Emeka Mbah
你的 'verification_code' 是从模型随机生成的吗?还是只是在迁移文件中填充了默认方法? - Cengkaruk
@Cengkaruk жҲ‘зҡ„verification_codeжҳҜеңЁз”ЁжҲ·жіЁеҶҢиҙҰжҲ·ж—¶з”ҹжҲҗзҡ„гҖӮе®ғжҳҜдёҖдёӘе”ҜдёҖзҡ„йҡҸжңәеӯ—з¬ҰдёІгҖӮеҸҜд»ҘеңЁжЁЎеһӢдёӯиҝҷж ·е®һзҺ°: public function setVerificationCodeAttribute($value) { $this->attributes['verification_code'] = md5(str_random(64) . time()*64); } - Emeka Mbah

18

Laravel在Illuminate\Foundation\Auth\RegistersUsers trait中提供了一个名为registered的空方法,用于简化此操作,只需按以下方式覆盖它:

首先添加一个新的通知:

<?php

namespace App\Notifications;

use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class UserRegisteredNotification extends Notification {

    public function __construct($user) {
        $this->user = $user;
    }

    public function via($notifiable) {
        return ['mail'];
    }

    public function toMail($notifiable) {
        return (new MailMessage)
            ->success()
            ->subject('Welcome')
            ->line('Dear ' . $this->user->name . ', we are happy to see you here.')
            ->action('Go to site', url('/'))
            ->line('Please tell your friends about us.');
    }

}

将此use行添加到您的RegisterController.php文件中:

use Illuminate\Http\Request;
use App\Notifications\UserRegisteredNotification;

并添加这个方法:

protected function registered(Request $request, $user) {
    $user->notify(new UserRegisteredNotification($user));
}

你完成了。


1
你在哪里添加新的通知? - Vinod Kumar
4
使用 Artisan 命令:php artisan make:notification UserRegisteredNotification。 - Sinan Eldem
3
这种做法更符合 Laravel 的风格,比 digilimit 的解决方案更好。 - Kiko Seijo
为什么在UserRegisteredNotification中的$this->user = $user处会显示“未定义变量:user”? - Jnanaranjan
我忘记在构造函数中传递$user了。现在它可以工作了。 - Jnanaranjan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接