Dewan159
Dewan159

Reputation: 3074

Laravel: How to get the recipient (Notifiable) from within the Notification?

I am using Laravel Notifications to broadcasts updates to the user. I am wondering if there is a way to get the Notifiable target of the notification from inside the notification itself.

Auth::user()->notify(
new TextNotification('Hi there!')
)

Now, I want to get the Notifiable instance (here is the User) inside the Notification's __construct. Does this object get passed to the notification at any point?

I know I can pass it to the notification class, but I am wondering if this is already done by Laravel.

Upvotes: 3

Views: 4065

Answers (3)

Noval Bayu Setiawan
Noval Bayu Setiawan

Reputation: 1

You don't have to specify notifiable id to neither redefine the broadcastOn() method. Its automatically handled by the Notification as explained here.

Notifications will broadcast on a private channel formatted using a {notifiable}.{id} convention. So, if you are sending a notification to an App\Models\User instance with an ID of 1, the notification will be broadcast on the App.Models.User.1 private channel.

Upvotes: 0

Borisu
Borisu

Reputation: 848

In this case the user is automatically inserted into the notification you're sending and you can accept it in the toArray and toMail methods.

// in TextNotification
public method toArray($notifiable)
{
    // $notifiable is the $user from Auth::user()
}

Upvotes: 3

Jinal Somaiya
Jinal Somaiya

Reputation: 1971

yes, you get $notifiable instance in Notification class.

for more details see this.

Upvotes: 1

Related Questions