Laravel 实现注册新用户时邮箱验证
实现注册时邮箱验证的方法有很多…
如果项目使用了 laravel 内置的 Auth 相关的控制器登录和注册,官方文档有更简单的方法…
本文手动实现发送邮件以及验证的功能…
前期准备
安装需要的组件
// 新建一个 Larave 项目
composer create-project laravel/laravel ./email_test
// 安装 Laravel ui 和 vue
composer require laravel/ui
php artisan ui vue --auth
// 安装相关依赖,编译 vue
npm install && npm run dev
// 数据库迁移
php artisan migrate
配置数据库
配置邮箱
方法一:使用 MailTrap
方法二:使用谷歌邮箱
.env
文件中修改相关信息
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com // 如果用 gmail 就改为 smtp.gmail.com
MAIL_PORT=465 // 下面的 ENCRYPTION 如果是 ssl,则为 465
MAIL_USERNAME=your-email@gmail.com // 修改为自己的邮箱地址
MAIL_PASSWOR=****** // 填写邮箱的授权码
MAIL_ENCRYPTION=ssl // 加密类型,可为不填或 ssl 或 tls,如果上面的 MAILER 选择 smtp,ENCRYPTION 填 ssl
MAIL_FROM_ADDRESS=your-email@gmail.com // 修改为自己的邮箱地址
MAIL_FROM_NAME=test // 发送邮件时显示的名字
谷歌邮箱授权码获取方式见
Gmail 官网文档
1. 数据库迁移文件添加字段
databse/migrations/2014_10_12_000000_create_users_table
中添加
$table->string('verification_code')->nullable();
$table->integer('is_verified')->default(0);
添加后如下
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('verification_code')->nullable();
$table->integer('is_verified')->default(0);
$table->rememberToken();
$table->timestamps();
});
}
重新迁移
php artisan migrate:refresh
此时数据库的
users
表中多了两个字段
2. 发送邮件到用户邮箱
(1) 添加视图页面 send-email.blade.php
resources/view/emails/send-email.blade.php
Hello {{$email_data['name']}}}
<br><br><br>
Please click the below link to verify your email and activate your account!
<br><br>
<a href="http://localhost:8000/verify?code={{$email_data['verification_code']}}">Click Here!</a>
<br><br>
Thank you!
<br>
(2) 新建 SignupMail, 返回 view 中的 send-email.blade.php
php artisan make:mail SignupMail
app/Mail/SignupEmail.php
如下
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class SignupMail extends Mailable
{
use Queueable, SerializesModels;
public function __construct($data)
{
$this -> email_data = $data;
}
public function build()
{
return $this
-> subject('Test Email Verification')
-> view('emails.send-email', ['email_data'=>$this->email_data]);
}
}
(3) RegisterController 中添加 register() 方法,使用 SignupMail
app/Http/Controllers/Auth/RegisterController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Mail\SignupMail;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\MailController;
use Illuminate\Http\Request;
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
public function register(Request $request)
{
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = Hash::make($request->password);
$user->verification_code = sha1(time());
$user->save();
if ($user != null)
{
$data = [
'name' => $user->name,
'verification_code' => $user->verification_code
];
Mail::to($user->email)->send(new SignupMail($data));
return redirect()->back();
}
// show error message
return redirect()->back();
}
3. 点击邮箱中的链接进行验证
(1) 新建路由
routes/web.php
Route::get('/verify', [App\Http\Controllers\Auth\RegisterController::class, 'verifyUser'])->name('verify.user');
(2) RegisterController.php 中添加 verifyUser() 方法
app/Http/Controllers/Auth/RegisterController.php
中
verifyUser()
如下
public function verifyUser(Request $request)
{
$verification_code = \Illuminate\Support\Facades\Request::get('code');
$user = User::where(['verification_code' => $verification_code])->first();
if ($user != null)
{
$user -> is_verified = 1;
$user -> save();
return view('emails.success');
}
return 'User not exist!';
}
(3) 新建视图 success.blade.php
recources/view/mails
中新建
success.blade.php
verification success
4. 只允许验证过的用户登录
app/controller/Auth/LoginController.php
中添加
credentials()
方法
public function credentials(Request $request)
{
return array_merge($request->only($this->username(), 'password'),['is_verified' => 1]);
}