I added a notification on created lifecycle hook on the model but it does not send the notification
Here is my booted method of the model.
protected static function booted(): void
{
static::created(function (Event $event) {
if ('event_type_id' === 3) {
Notification::send(auth()->user(), new NewEvent($event));
}
});
}
And here is the notification class
class NewEvent extends Notification
{
use Queueable;
public $event;
/**
* Create a new notification instance.
*/
public function __construct(Event $event)
{
$this->event = $event;
}
/**
* Get the notification's delivery channels.
*
* @return array<int, string>
*/
public function via(object $notifiable): array
{
return ['mail', TwitterChannel::class, NovaChannel::class];
}
public function toTwitter(mixed $notifiable): TwitterMessage
{
return new TwitterStatusUpdate($this->event->brideSideFullName);
}
public function toNova()
{
return (new NovaNotification)
->message($this->event->brideSideFullName)
->icon('emoji-happy')
->type('info');
}
/**
* Get the mail representation of the notification.
*/
public function toMail(object $notifiable): MailMessage
{
return (new MailMessage)
}
It looks like there is a typo in the booted method. The if statement is checking if the string 'event_type_id' is equal to the integer 3, which will always be false. It should be checking if the value of the event_type_id attribute is equal to 3. Here's the corrected code:
protected static function booted(): void
{
static::created(function (Event $event) {
if ($event->event_type_id === 3) {
Notification::send(auth()->user(), new NewEvent($event));
}
});
}
Also, make sure that the auth()->user() function is returning the correct user. If you're running this code in a console command or a job, for example, there may not be an authenticated user. In that case, you'll need to pass in a user object manually. Here's an example:
$user = User::find(1); // replace 1 with the ID of the user you want to notify
Notification::send($user, new NewEvent($event));