Laravel 10 - Welcome Notification Email

Touseef Afridi
11 Sep 24

Laravel 10 - Welcome Notification Email

In this tutorial, we’ll explore how to send a welcome email notification in Laravel 10, 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 email notifications in a Laravel 10 application. You'll create a new Laravel project, install Laravel Breeze for authentication, and set up a custom WelcomeMailNotification to send a welcome email when a user registers. You'll configure Mailtrap for email testing and update the RegisteredUserController to trigger the notification. Finally, you'll test the system by running the development server and verifying that the welcome email is sent. By the end, you'll have a fully functional email notification system in Laravel 10. You'll also learn how to customize email views and pass dynamic user data, giving you flexibility in how emails are sent. This setup provides a strong foundation for implementing other notification types and email features in your Laravel applications.

Step # 1 : Create a New Laravel Project.

Start by creating a new Laravel project named notifications. You can use either the Laravel installer or Composer. If you have Laravel globally installed you can use below command.
laravel new notifications
If you prefer using Composer, use the following command.
composer create-project laravel/laravel --prefer-dist notifications
When you run either command, it will create a new Laravel project called notifications, including all the default files and configurations needed to start development.

Step # 2 : Open the Project Directory.

After creating the project, open a terminal (such as Git Bash) and navigate to your project's root directory.
cd c:xampp/htdocs/notifications
Make sure you're inside the project folder to execute the upcoming commands.

Step # 3 : Install Breeze Authentication.

To send a welcome notification upon user registration, we need to first set up user authentication using Laravel Breeze. Start by installing the Laravel Breeze package.
composer require laravel/breeze --dev
After installing the package, install the Breeze authentication scaffolding.
php artisan breeze:install
You will be prompted to select a stack (e.g., Blade or Inertia). Based on your selection, you may be asked to choose additional options, such as enabling dark mode or Pest testing, if applicable. Next, install the frontend dependencies and compile the assets.
npm install && npm run dev
Open a new terminal window or tab (keeping the Vite server running), navigate to the project directory again, and run the following command to migrate the table.
php artisan migrate
At this point, your Laravel project has authentication ready, and you can proceed to set up the welcome notification.

Step # 4 : Create Notification.

We need to create a notification that will be sent when a new user registers. Run the following command to generate a new notification class.
php artisan make:notification WelcomeMailNotification
This will create a Notifications folder (if it doesn't already exist) inside the app directory, and generate a file named WelcomeMailNotification.php. Next, open the WelcomeMailNotification.php file and update the toMail method to define the email content.
    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 method builds the email message by adding a welcome line, an action button linking to your site's homepage, and a closing thank-you line.

Step # 5 : Set Up a Mailtrap Account.

  1. Go to Mailtrap : https://mailtrap.io/ and create a free account.
  2. After signing up, create a new project to manage your testing emails.
  3. Inside the project dashboard, you will find all the SMTP credentials needed for the next steps.


Step # 6: Update .env.

In your .env file, replace the placeholders with your Mailtrap credentials to enable email testing.
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}"
Updating the .env file with your Mailtrap credentials configures Laravel to use Mailtrap for sending test emails, allowing you to verify email functionality without sending real emails during development.

Step # 7 : Update RegisteredUserController.

Open RegisteredUserController.php and import the WelcomeMailNotification class at the top of the file.
use App\Notifications\WelcomeMailNotification;
Next, update the store method as follows to send the welcome email after the user registers.
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(RouteServiceProvider::HOME);
}
This updates the store method to trigger the WelcomeMailNotification immediately after a user registers, ensuring they receive a welcome email.

Step # 8 : It's time to test.

Start the Laravel development server by running the following command.
php artisan serve
Create an account and you will receive welcome notification email in Mailtrap.


To pass a custom view with the notification, you’ll need to update the store method in RegisteredUserController. First, ensure that the method handles the validation and user creation process correctly. Here’s how the method should look after incorporating the necessary changes.
    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, you need to update the WelcomeMailNotification.php file to handle the custom email view. The file should be modified as follows to specify the view you want to use for the email notification.
<?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 Our Platform')
            ->view('welcome-email', ['user' => $this->user]);
            // Use custom view
        }
        public function toArray($notifiable)
        {
            return [];
        }
    }
Finally, create the custom email view welcome-email.blade.php as specified in the toMail method. This view will define the structure and design of the email content.
<!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>



Conclusion

By following this guide, you’ve successfully set up a Laravel 10 project with Breeze authentication and Mailtrap for email testing. Your project now includes key features like user registration, login functionality, and email notifications, providing a solid foundation for further development. With authentication in place, you can focus on adding features like custom email views, user profiles, and other enhancements. As your application grows, explore additional Laravel features to elevate it to the next level. Whether you’re building a simple app or scaling up, Laravel’s flexibility allows you to continuously improve your system.
For more details, refer to the official Laravel documentation.
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