You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel新增用户功能:添加含Token与创建密码链接的欢迎邮件通知

解决方案

步骤1:调整用户创建逻辑(控制器代码修改)

移除管理员创建用户时的密码验证,不再预先设置用户密码,改为生成密码重置Token并传递给通知类:

// Save New User
public function addNewUser(Request $request)
{
    $request->validate([
        'name'          => 'required|string|max:255',
        'email'         => 'required|string|email|max:255|unique:users',
        'role_name'     => 'required|string|max:255',
        'status'        => 'required|string|max:255',
        'image'         => 'required|image',
        // 移除密码相关验证规则
    ]);
    DB::beginTransaction();
    try{
        $dt             = Carbon::now();
        $todayDate      = $dt->toDayDateTimeString();

        $image = time().'.'.$request->image->extension();
        $request->image->move(public_path('/assets/images'), $image);

        $user = new User;
        $user->name             = $request->name;
        $user->email            = $request->email;
        $user->join_date        = $todayDate;
        $user->role_name        = $request->role_name;
        $user->status           = $request->status;
        $user->avatar           = $image;
        // 不设置初始密码,由用户自行设置
        $user->save();
        DB::commit();

        // 生成密码重置Token
        $resetToken = \Illuminate\Support\Facades\Password::createToken($user);
        // 将用户和Token传入通知类
        $user->notify(new WelcomeEmailNotification($user, $resetToken));

        Toastr::success('Created Successfully','Success');
        return redirect()->route('userManagement');
    }catch(\Exception $e){
        DB::rollback();
        Toastr::error('User add new account fail','Error');
        return redirect()->back();
    }
}

步骤2:修改通知类(WelcomeEmailNotification.php)

更新构造函数接收用户和Token参数,在邮件内容中添加密码重置链接和Token:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class WelcomeEmailNotification extends Notification
{
    use Queueable;

    protected $user;
    protected $resetToken;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($user, $resetToken)
    {
        $this->user = $user;
        $this->resetToken = $resetToken;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        // 构建密码重置链接(使用Laravel默认密码重置路由)
        $resetUrl = route('password.reset', [
            'token' => $this->resetToken,
            'email' => $this->user->email
        ]);

        return (new MailMessage)
                    ->subject('欢迎加入我们的平台')
                    ->line("您好,{$this->user->name}!管理员已为您创建账号,请点击下方链接设置登录密码:")
                    ->action('设置密码', $resetUrl)
                    ->line("您的密码重置Token:{$this->resetToken}")
                    ->line('若您未申请创建账号,请忽略此邮件。');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

步骤3:必要的配置检查

  1. 用户模型验证:确保App\Models\User模型已实现Illuminate\Contracts\Auth\CanResetPassword接口(Laravel默认User模型已包含此实现)。
  2. 数据库字段调整:若用户表password字段设置为NOT NULL,需修改迁移文件将其改为nullable,再执行迁移更新表结构:
    // 修改用户表迁移文件中的password字段
    $table->string('password')->nullable();
    
    执行迁移命令:
    php artisan migrate
    
  3. 路由确认:确保项目中存在默认的密码重置路由(可通过php artisan route:list查看,路由名称应为password.reset)。

内容的提问来源于stack exchange,提问作者Jay-ar Cristobal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 17:48:29