Laravel 11 - Welcome Notification Email

Touseef Afridi
17 Sep 24

Laravel 11 - Welcome Notification Email

In this tutorial, we’ll explore how to send a welcome email notification in Laravel 11, enhancing user engagement and providing a personalized experience


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

This guide walks you through setting up a welcome email notification in a Laravel application with Breeze authentication. You'll begin by creating a fresh Laravel project and setting up Breeze for authentication. After that, you'll generate a notification for the welcome email and configure Mailtrap for email testing. You'll also modify the RegisteredUserController to trigger the welcome email when a new user registers. Finally, the guide covers testing the email functionality by creating a user account and verifying the welcome notification in Mailtrap. You’ll also learn how to customize the email view to personalize the welcome message for users.

Step # 1 : Set Up Laravel Project with Breeze Authentication.

To trigger a welcome email upon user registration, we first need to set up authentication. This is done by installing Laravel Breeze during project creation.
If Laravel is globally installed, run.
laravel new notification
Otherwise, use Composer.
composer create-project laravel/laravel --prefer-dist notification
After running one of the above commands, you'll be prompted.
  • Would you like to install the starter kit? — Select Breeze.
  • After selecting Breeze, you'll be asked to choose your stack? — Select Blade.
  • After selecting Blade, you'll be asked for dark mode support? — Select No.
  • After selecting No, you'll be asked about testing framework? — Select PHPUnit.
  • After selecting PHPUnit, you'll be asked if you want to initialize git repo? — Select No.
  • After selecting no, you'll be asked to select the database for your application? — Select Mysql.
  • After selecting MySql, you'll be asked if you want to run the default database migration? — Select Yes.

This step sets up a fresh Laravel project with Breeze authentication. If Laravel is globally installed, use the laravel new command for quick setup. Alternatively, use Composer with create-project to install Laravel. During setup, select Breeze as the starter kit, Blade for the stack, No for dark mode support, PHPUnit for testing, MySQL for the database, and confirm running the default migrations.

Step # 2 : Access the project.

Open a terminal (e.g., Git Bash) and navigate to your Laravel project's root folder.
cd c:xampp/htdocs/notification
This step ensures you're in the correct directory to run Laravel commands and work with your project's files.

Step # 3 : Create the Notification.

To generate a new notification, run the following command.
php artisan make:notification WelcomeMailNotification
This will create a Notifications folder and a WelcomeMailNotification.php file within the app directory. Open the WelcomeMailNotification.php file and update the toMail method as shown below.
    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage)
                    ->line('Welcome To Code Shotcut')
                    ->action('Action Url', url('/'))
                    ->line('Thank you for using Code Shotcut!');
    }
This step customizes the notification content that will be sent via email when triggered.

Step # 4 : Create a Mailtrap Account.

  • Visit https://mailtrap.io and sign up for an account.
  • After registration, create a new project for testing purposes.
  • Inside the project, you'll find all the required details for the next steps.


Step # 5: Update .env Configuration.

In your .env file, replace the placeholders with your Mailtrap credentials for testing emails.
MAIL_MAILER=smtp
MAIL_HOST=sandbox.smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME="Your Mailtrap username"
MAIL_PASSWORD="Your Mailtrap password"
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="Your email address"
MAIL_FROM_NAME="${APP_NAME}"
By updating the .env file with your Mailtrap credentials, you configure Laravel's mailer to use Mailtrap for sending test emails. This allows you to verify the email functionality without actually sending real emails, ensuring that everything works as expected during development.

Step # 6 : Modify RegisteredUserController.

Navigate to RegisteredUserController.php and import the WelcomeMailNotification class.
use App\Notifications\WelcomeMailNotification;
Then, update the store method as follows.
public function store(Request $request): RedirectResponse
{
    $request->validate([
        'name' => ['required', 'string', 'max:255'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'confirmed', Rules\Password::defaults()],
    ]);
    $user = User::create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => Hash::make($request->password),
    ]);
    event(new Registered($user));
    //Send Welcome Mail Notification
    $user->notify(new WelcomeMailNotification());
    Auth::login($user);
    return redirect(route('dashboard', absolute: false));
}
In this step, we modify the store method of RegisteredUserController.php to send a welcome email when a new user registers. After validating the registration input and creating the user, the WelcomeMailNotification is triggered to notify the user via email.

Step # 7 : It's time to test.

Now, it's time to test the welcome email functionality. Start the Laravel development server by running the following command.
php artisan serve
After the server starts, create a new user account. You should receive the welcome notification email in Mailtrap.


To send a custom view in the email, modify the store method in the RegisteredUserController as follows.
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);
        event(new Registered($user));
        //Send Welcome Mail Notification and pass user.
        $user->notify(new WelcomeMailNotification($user));
        Auth::login($user);
        return redirect(route('dashboard', absolute: false));
    }
Next, update the WelcomeMailNotification.php file as shown below.
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class WelcomeMailNotification extends Notification
{
    use Queueable;
    protected $user;
    // Constructor to accept the user object
    public function __construct($user)
    {
        $this->user = $user;
    }
    public function via($notifiable)
    {
        return ['mail'];
    }
    // Customize the email using a view and pass the user data
    public function toMail($notifiable)
    {
        return (new MailMessage)
        ->subject('Welcome to Code Shotcut')
            ->view('welcome-email', ['user' => $this->user]);
            // Use custom view
        }
        public function toArray($notifiable)
        {
            return [];
        }
    }
Create a custom view for the email as defined in the toMail method. Save this as welcome-email.blade.php.
<!DOCTYPE html>
<html>
<head>
    <title>Welcome to Code Shotcut</title>
</head>
<body>
    <h1>Welcome, {{ $user->name }}!</h1>
    <p>Thank you for joining us.</p>
    <p>Your email is: {{ $user->email }}</p>
</body>
</html>
Now, create a user and you should receive an email with the updated custom view.




After testing the welcome email functionality, you will receive the email in Mailtrap if everything is set up correctly. If you’ve implemented a custom email view, the welcome email will be displayed with your personalized content. This confirms that the email notification is being sent and formatted as intended. You can then proceed to make any final adjustments or enhancements to the email content, such as adding more dynamic data or improving the design of the email view, before deploying your application to production.

Conclusion

By following this guide, you’ve successfully set up a welcome email notification in your Laravel application using Breeze authentication. Your application now automatically sends a personalized welcome email to users upon registration, improving user experience and engagement. You’ve also learned how to configure Mailtrap for testing email functionality, update the .env file with the correct SMTP credentials, and test the email system in a local development environment. This setup ensures that email notifications work smoothly and can be customized as needed for a more personalized user experience.
For more details, refer to the Laravel documentation on notifications and email sending.
Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering