Search code examples
laravellaravel-6laravel-authenticationlaravel-maillaravel-notification

Laravel Auth, Passing user credentials to Notification Class after registering


I am trying to pass User details to my notification so I can say: Dear User name, but couldnt figure it how. Also, I am looking forward to getting the default URL when verifying the user. So, basically I only wanted to change the first ->line() in my toMail function.

In User Model:

public function sendEmailVerificationNotification()
{
    $this->notify(new CustomVerifyEmail($this->user));
}

In CustomVerifyEmail Class

public $user;
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * Get the notification's delivery 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)
                    ->line('The introduction to the notification.'.$this->user->email)
                    ->action('Notification Action', url('/'))
                    ->line('Thank you for using our application!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }

Solution

  • You should be able to get the 'name' from the $notifiable that is passed to the toMail call, assuming it will be your User model:

    line('The introduction to the notification.'. $notifiable->name)
    

    For ways to customize the MailMessage that is sent I have added an answer to your other question. Laravel Auth, Getting the default URL that is passed in Notification