我对Laravel不熟悉,目前正在使用Laravel 5。为了用户注册和登录,我想使用Laravel的默认系统。但是,我需要在此基础上扩展以下两个功能:
- 用户注册后将收到一封电子邮件。
- 在保存用户注册信息时,我需要在另一个角色表格中添加一个条目(我已经使用Entrust包进行角色管理)。
如何实现这些功能?
你可以修改位于 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
注意:您需要为验证创建路由/控制器
verification_code
жҳҜеңЁз”ЁжҲ·жіЁеҶҢиҙҰжҲ·ж—¶з”ҹжҲҗзҡ„гҖӮе®ғжҳҜдёҖдёӘе”ҜдёҖзҡ„йҡҸжңәеӯ—з¬ҰдёІгҖӮеҸҜд»ҘеңЁжЁЎеһӢдёӯиҝҷж ·е®һзҺ°: public function setVerificationCodeAttribute($value) { $this->attributes['verification_code'] = md5(str_random(64) . time()*64); }
- Emeka MbahLaravel在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));
}
你完成了。