Laravel密码重置功能开箱即用,只需配置User模型、运行迁移、配置邮件、注册Auth路由并可选自定义视图;核心是确保数据库、邮件、路由与视图四环节协同工作。

Laravel 自带的密码重置功能开箱即用,只需少量配置和几条 Artisan 命令就能跑通完整流程:用户点击“忘记密码” → 填写邮箱 → 收到含一次性重置链接的邮件 → 点击链接跳转到新密码表单 → 提交完成重置。关键在于理解各组件如何协作,而不是从零手写逻辑。
确保你的 User 模型实现了 Illuminate\Contracts\Auth\CanResetPassword 接口(Laravel 默认已实现)。检查 app/Models/User.php 是否包含:
php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\CanResetPassword;
class User extends Authenticatable implements CanResetPassword
{
use Notifiable;
}
执行以下命令生成密码重置数据表:
php artisan make:migration create_password_reset_tokens_tablepassword_reset_tokens 表(Laravel 10.27+ 默认表名),内容类似:Schema::create('password_reset_tokens', function (Blueprint $table) {
$table->string('email')->primary();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
然后运行:php artisan migrate
确认邮箱服务已配置(如 SMTP 或 Mailgun),在 .env 中设置:
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=you@gmail.com
MAIL_PASSWORD=your-app-password
MAIL_ENCRYPTION=tls
免费 盛世企业网站管理系统(SnSee)系统完全免费使用,无任何功能模块使用限制,在使用过程中如遇到相关问题可以去官方论坛参与讨论。开源 系统Web代码完全开源,在您使用过程中可以根据自已实际情况加以调整或修改,完全可以满足您的需求。强大且灵活 独创的多语言功能,可以直接在后台自由设定语言版本,其语言版本不限数量,可根据自已需要进行任意设置;系统各模块可在后台自由设置及开启;强大且适用的后台管理支
0
Laravel 提供了现成的认证脚手架。推荐使用:
php artisan make:auth(Laravel ≤ 5.8)laravel/breeze 或 laravel/jetstream,它们已预置完整密码重置页面与逻辑routes/web.php 中包含:Auth::routes(['reset' => true]);
这会自动注册以下路由:
GET /password/reset → 显示邮箱输入页(ForgotPasswordController@showLinkRequestForm)POST /password/email → 发送重置邮件(ForgotPasswordController@sendResetLinkEmail)GET /password/reset/{token} → 显示新密码表单(ResetPasswordController@showResetForm)POST /password/reset → 处理新密码提交(ResetPasswordController@reset)复制默认视图到项目中以便修改:
php artisan vendor:publish --tag=laravel-notifications(发布通知模板)php artisan vendor:publish --tag=laravel-mail(发布邮件样式)resources/views/auth/passwords/,包括:email.blade.php(邮件正文)、reset.blade.php(重置表单)、request.blade.php(邮箱请求页)例如修改 reset.blade.php 中的表单字段(需保留隐藏的 token 和 email):
@csrf
red>
基本上就这些。不需要重写核心逻辑,重点是配对路由、数据库、邮件和视图四个环节。中间任何一步断开(比如没发邮件、token 过期、表单漏字段)都会导致失败,调试时优先查日志和邮件驱动是否生效。
以上就是Laravel如何实现用户密码重置功能?(完整流程代码)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号