Add user name in confirm mail notification laravel

To add the user's name in the confirmation email notification in Laravel, you can modify the App\Notifications\VerifyEmail notification class.

Here's an example of how you can do it:

  1. Open the VerifyEmail notification class located in app/Notifications directory.

  2. Add the following code to the __construct method:

    public function __construct(User $user)
    {
     $this->user = $user;
    }

    This will inject the User model instance into the notification.

  3. Modify the toMail method to include the user's name:

    public function toMail($notifiable)
    {
     $url = url(route('verification.verify', [
         'id' => $this->user->getKey(),
         'hash' => $this->user->getEmailVerificationToken(),
     ]));
    
     return (new MailMessage)
         ->subject('Verify Email Address')
         ->greeting('Hello '. $this->user->name. '!')
         ->line('Please click the button below to verify your email address.')
         ->action('Verify Email Address', $url)
         ->line('If you did not request this, please ignore this email.');
    }

    In this example, we're using the name attribute of the User model to include the user's name in the greeting.

  4. Run the following command to generate a new migration for the email verification table:

    php artisan make:migration add_name_to_users_table
  5. Open the generated migration file and add the following code:

    public function up()
    {
     Schema::table('users', function (Blueprint $table) {
         $table->string('name')->nullable()->after('email');
     });
    }

    This will add a name column to the users table.

  6. Run the migration:

    php artisan migrate
  7. Update the User model to include the name attribute:

    public function getNameAttribute()
    {
     return $this->attributes['name'];
    }
  8. Finally, run the following command to send the confirmation email with the user's name:

    php artisan tinker

    In the Tinker shell, you can use the following code to send the confirmation email:

    $user = App\User::find(1);
    $user->sendEmailVerificationNotification();

    This should send an email with the user's name included in the greeting.

That's it! From now on, when a user registers and needs to confirm their email address, they will receive an email with their name included in the greeting.