lundi 3 septembre 2018

Differ view data based on recipient for Laravel emails when using multiple recipients

I am trying to send through Laravel a single email with multiple recipients, but with different view data based on the recipient.

I need to show, for example, the firstname of the user receiving the email, instead of all of them.

This is the code:

protected $hints = [
    ['game_hint_2', 'game_hint_3'],
    ['game_hint_4'],
    ['game_hint_5', 'game_hint_6'],
    ['game_hint_7', 'game_hint_8'],
    ['game_hint_9', 'game_hint_10']
];

$users = $this->users->query()->whereConfirmed(true)->get();

$emails = $users->pluck('email');

Mail::bcc($users->pluck('email'))->send(
    new GameHintsEmail($hints[$dayIndex])
);

How do I specify view data for each and every recipient?

Basically, for each recipient, a replacement tag in the view needs to be filled based on the user's email, to achieve a result similar to Hello *firstname*!

This is the mailable:

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

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

    return $this
        ->view('emails.hints.game_hint')
        ->text('emails.hints.game_hint_plain')
        ->with($data)
        ->subject($data['subject']);
}

protected function __buildViewData()
{
    $data = [];

    $data['subject'] = "Game Hints! Name 2018 Competition";
    $data['hints'] = $this->gameHints;

    if ($this->bcc && !empty($this->bcc)) {
        $data['userEmail'] = $this->getUserEmail();
    }

    return $data;
}

protected function getUserEmail()
{
    if ($this->to && !empty($this->to)) {
        return $this->bcc[0]['address'];
    }
}

getUserEmail only allows me to get the first recipient data, but it's not what I want to do.

Is it even possible?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire