Introducing the Mail Channel in Notifications in Laravel 11
In Laravel 11, one of the ways to send notifications is by using the Mail channel. This feature allows you to inform your users about specific events via email. Notifications can contain important information that the user needs to stay updated on, such as changes in account details or personal messages.
To use this capability, you must first ensure that the settings related to mail in the config/mail.php
file are correctly configured. These settings include SMTP server information, port, and security settings. If the settings are not properly configured, notifications will not be sent.
After rolling out mail configuration, you need to create a notification class. This class includes the notification content and can specify what data should be displayed in the notification. The class that you create can include attributes for formatting the notification that matches the mail format.
When you create this class, you can send notifications to users who want to receive notifications, simply by using the notify
method.
Example code for email notifications in Laravel 11
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Channels\Mail;
class AccountCreatedNotification extends Notification {
public function via($notifiable) {
return [Mail::class];
}
public function toMail($notifiable) {
return (new MailMessage)
->subject('Your account has been created')
->line('Welcome! Your account has been successfully created.')
->action('Log in to your account', url('/login'))
->line('If this is not you, please disregard this message.');
}
}
Letter explanations
Letter 1: In this letter, we will import the space where notifications exist.
Letter 2: In this letter, we can import the Mail channel to use it.
Letter 4: We define the notification class itself. This class can include different attributes.
Letter 5: This letter specifies which channel the notification will be sent through, which here is the Mail channel.
Letter 7: This letter will create the content of the email notification.
Letter 8: Here, we specify the content of the email.
Letter 9: In this letter, we describe the message that will appear in the email.
Letter 10: This letter creates tokens that redirect the user to the login page.
Letter 11: Finally, we inform the user that if this email is not for them, they can ignore it.