To create a new notification class in Laravel 9, you can use the make:notification
Artisan command. This command will generate a new notification class in the app/Notifications
directory.
Here is an example of how to use the make:notification
command to create a new notification class:
php artisan make:notification MyNotification
This will create a new notification class called MyNotification
in the app/Notifications
directory. You can then open this file and customize it to define the email subject, body, and any other details of the notification.
Here is an example of a basic notification class:
<?php
namespace App\Notifications;
use Illuminate\Notifications\Notification;
class MyNotification extends Notification
{
/**
* The subject of the notification.
*
* @var string
*/
public $subject;
/**
* The body of the notification.
*
* @var string
*/
public $body;
/**
* Create a new notification instance.
*
* @param string $subject
* @param string $body
* @return void
*/
public function __construct($subject, $body)
{
$this->subject = $subject;
$this->body = $body;
}
/**
* Get the notification's channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->subject($this->subject)
->line($this->body);
}
}
In this example, the MyNotification
class extends the Illuminate\Notifications\Notification
class and defines the via
and toMail
methods. The via
method specifies that this notification should be sent via email, and the toMail
method defines the email subject and body using the values provided in the constructor.
To send a notification email in Laravel, you can use the notify
method on a user instance. This method accepts an instance of a notification class, which defines the email content and recipients.
Here is an example of how to use the notify
method to send a notification email:
<?php
use App\Notifications\MyNotification;
use App\User;
// Get the user instance
$user = User::find(1);
// Create a new notification instance
$notification = new MyNotification('Subject of your Notification', 'This is the body of the email');
// Send the notification
$user->notify($notification);
For more information on creating and using notifications in Laravel, you can refer to the Laravel documentation on notifications.