user936965
user936965

Reputation:

Laravel 5.5 mail with username in it

I think I miss something really simple here, but I have a script like this:

\Mail::to( User::all() )
             ->send( new NotificationEmail($notification) );

class NotificationEmail extends Mailable {
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @param Notification $notification
     *
     */
    public function __construct( Notification $notification ) {
        $this->notification = $notification;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build() {
        $notification = $this->notification;

        return $this
            ->from( [
                'address' => \env( 'MAIL_DEFAULT_SENDER' ),
                'name'    => \env( 'APP_NAME' )
            ] )
            ->view( 'email.notification.ready' );
    }
}

Now I'd like the email message to start with something like

Dear {firstname of the user} But I have no idea how to get the firstname of user who is going to get that email. Is there any way to figure that out?

Upvotes: 3

Views: 1291

Answers (1)

Ben
Ben

Reputation: 5129

It is not a recommended way to send a email to all users, because who receive the email can see all the recipients and, they receive the same message that you cannot customize to add first name of the user.

You need to create separate Mailable to each user and queue all the Mailable. Sending email to all users separately is time-consuming task, workers are need to process the queue in background.

$users = User::all();
foreach ($users as $user) {
    Mail::to($user)->queue(new NotificationEmail($notification, $user));
}

And now you can pass the $user instance, and first name of the user is available on the view:

public function __construct( Notification $notification , User $user) {
    $this->notification = $notification;
    $this->user = $user;
}

public function build() {
    $notification = $this->notification;

    return $this
        ->from( [
            'address' => \env( 'MAIL_DEFAULT_SENDER' ),
            'name'    => \env( 'APP_NAME' )
        ] )
        ->view( 'email.notification.ready' , [
            'user' => $this->user
        ]);
}

Upvotes: 0

Related Questions