Laravel Anonymous Notification - How to get route value from Laravel Notification::route() function?

2.5k Views Asked by At
Notification::route('sms', $mobileNumber)->notify(new SmsNotification($content));

Optimally you should use routeForNotificationSms in your Notifiable model (eg: User) to obtain the value of the route. But since I am sending the notification to unregistered user, I am trying to access the $mobileNumber variable in my channel without needing to go to the User model. If I try to access the values in the array I am getting and error

Cannot use object of type Illuminate\Notifications\AnonymousNotifiable as array

How do I access the value within the Notification::route parameter from the channel directly?

1

There are 1 best solutions below

0
On

From your channel, the send() method is passed the notifiable (in this case an instance of AnonymousNotifiable and the notification. The notifiable contains an array indexed by channel, where you can get this route information.

class SmsNotificationChannel
{
    public function send(mixed $notifiable, Notification $notification): void
    {
        $route = $notifiable->routes[self::class] ?? null;
        if ($route) {
            // do your thing
        }
    }
}

This assumes you are calling the anonymous notification with the full class name:

Notification::route(SmsNotificationChannel::class, $mobileNumber)
    ->notify(new SmsNotification($content));

You will have to experiment to see how it behaves with short names like "sms" in your original code. I'm not sure if it will still index by class name or use the short name.