龙空技术网

教材网站开发实录(9)Laravel邮箱验证

阮文武053 148

前言:

现时你们对“phpemail验证”大体比较珍视,小伙伴们都想要分析一些“phpemail验证”的相关知识。那么小编同时在网摘上收集了一些对于“phpemail验证””的相关知识,希望各位老铁们能喜欢,小伙伴们一起来学习一下吧!

前言

目前还没有开通第三方登录的权限,先用邮箱做一下用户验证。而且邮箱也是个不错的工具,适当的时候可以给用户发送消息提醒。

配置邮箱认证

Laravel自带的MustVerifyEmail可以帮助我们完成这项工作。

在user这个model中实现Illuminate\Contracts\Auth\MustVerifyEmail这个接口:

class User extends Authenticatable implements MustVerifyEmail

然后再在其中使用use Illuminate\Auth\MustVerifyEmail as MustVerifyEmailTrait这个trait。

use MustVerifyEmailTrait;

MustVerifyEmail的作用是定义接口。MustVerifyEmailTrait的作用是实现它的方法。

完整的model现在长这样:

<?phpnamespace App\Models;use Illuminate\Contracts\Auth\MustVerifyEmail;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Foundation\Auth\User as Authenticatable;use Illuminate\Notifications\Notifiable;use Laravel\Sanctum\HasApiTokens;use Illuminate\Auth\MustVerifyEmail as MustVerifyEmailTrait;class User extends Authenticatable implements MustVerifyEmail{    use HasApiTokens;    use HasFactory;    use Notifiable;    use MustVerifyEmailTrait;    ...

配置完这些后,user这个model就可以使用以下四个方法了:

hasVerifiedEmail()

检测用户 Email 是否已认证;markEmailAsVerified()

将用户标示为已认证;sendEmailVerificationNotification()

发送 Email 认证的消息通知,触发邮件的发送;getEmailForVerification()

获取发送邮件地址,提供这个接口允许你自定义邮箱字段配置mailhog

我们使用mailhog来做邮箱测试,它不需要我们配置邮件服务器,发送的所有邮件都可以在mailhog前台查看、管理。

Homestead自带了这个工具,而且服务不需要配置,直接就开启了,访问8025端口就可以看到界面。

修改.env

MAIL_MAILER=smtpMAIL_HOST=localhostMAIL_PORT=1025MAIL_USERNAME=nullMAIL_PASSWORD=nullMAIL_ENCRYPTION=nullMAIL_FROM_ADDRESS="awen@ruanwenwu.com.cn"MAIL_FROM_NAME="${APP_NAME}"

注意,邮件服务的端口是1025。8025是hotdog图形界面服务的端口。

测试注册汉化

修改resource/lang/zh_CN.json文件:

"Hello!": "您好!",    "Verify Email Address": "验证邮箱地址",    "Whoops!": "糟糕!",    "Please click the button below to verify your email address.": "请点击下面的按钮验证您的邮箱地址。",    "If you did not create an account, no further action is required.": "如果您没有创建账号,就不需要做任何操作。",    "Regards": "此致",    "If you're having trouble clicking the \":actionText\" button, copy and paste the URL below\ninto your web browser:": "如果\":actionText\"按钮点不了,请粘贴下面的网址到您的浏览器中进行访问。"

其实我们装一个语言包overtrue/laravel-lang就可以全部翻译,不用我们一个个修改了:

composer require "overtrue/laravel-lang:~5.x-dev"

装完发布一下资源:

php artisan lang:publish zh_CN
一些补充

这个消息推送系统挺复杂,一时半会还不能完全弄明白。记录几个重要的文件及方法。

邮件信息生成:\Illuminate\Auth\Notifications\VerifyEmail::buildMailMessage邮件模板:

vendor/laravel/framework/src/Illuminate/Notifications/resources/views/email.blade.php:47

标签: #phpemail验证