laravellaravel-notification

How can I send notification with User's email without creating the user in db?


On Laravel 10 site I need to send an email to user which could be not in db.users. I send notification with User, which I create in memory.

$post = $postAddedEvent->post;
$user = User::factory()->make();
$user->name = $post->getAttribute('user_name');
$user->email = $post->getAttribute('user_email');

Notification::send($user, new NewPostSentToUserNotification(
    post: $post
));

But have an error :

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'notifiable_id' cannot be null
INSERT INTO
  `notifications` (
    `id`,
    `type`,
    `data`,
    `read_at`,
    `notifiable_id`,
    `notifiable_type`,
    `updated_at`,
    `created_at`
  )
VALUES
  (
    5fb0da17 - 50ae - 415c - b10f - 5f03f9083761,
    App \ Notifications \ admin \ NewPostSentToUserNotification,
    [ ],
    ?,
    ?,
    App \ Models \ USER,
    2024 -06 -28 12: 57: 18,
    2024 -06 -28 12: 57: 18
  )

I would not like to save this new user in db, or create, send notification and delete after that. Are there some better decision ?

"laravel/framework": "^10.48.12",

Solution

  • use On-Demand Notifications

    Sometimes you may need to send a notification to someone who is not stored as a "user" of your application. Using the Notification facade's route method, you may specify ad-hoc notification routing information before sending the notification:

    Notification::route('mail', 'taylor@example.com')
      ->notify(new NewPostSentToUserNotification(post: $post));
    

    or

    If you would like to provide the recipient's name when sending an on-demand notification to the mail route, you may provide an array that contains the email address as the key and the name as the value of the first element in the array:

    Notification::route('mail', [
        'barrett@example.com' => 'Barrett Blair',
    ])->notify(new NewPostSentToUserNotification(post: $post));