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:
-
Open the
VerifyEmail
notification class located inapp/Notifications
directory. -
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. -
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 theUser
model to include the user's name in the greeting. -
Run the following command to generate a new migration for the email verification table:
php artisan make:migration add_name_to_users_table
-
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 theusers
table. -
Run the migration:
php artisan migrate
-
Update the
User
model to include thename
attribute:public function getNameAttribute() { return $this->attributes['name']; }
-
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.