Skip to content
Advertisement

multiple recipients email sent with htmlspecialchars() expects parameter error

I have a form, in which when I fill and submit, it’s sent email to multiple recipient, when I do that I get this error htmlspecialchars() expects parameter 1 to be string, array given (View: C:wamp64wwwstarresourcesviewsemailsemail_invite_template.blade.php below is my code:

The Form

<input name="iname[]" class="form-control" type="text" placeholder="Name" > 
<input name="iemail[]" class="form-control" type="text" placeholder="Email" >
<input type="submit" value="Send Invite" >

SendEmail

class SendEmail extends Mailable
{
    use Queueable, SerializesModels;
  
    public $data;
   
    public function __construct($data)
    {
        $this->data = $data;
    }
   
    public function build()
    {
        return $this->subject('Invitation to Mase')
        ->markdown('emails.email_invite_template')
        ->with('data', $this->data);
    }
}

Controller

public function storeInvite(Request $request)
{

    $eventid = $request->get('eventid');
    $iname = $request->get('iname');
    $iemail = $request->get('iemail');

    $data = array(
        'dname'      =>  $request->iname,
        'demail'   =>   $request->iemail
    );

    foreach($data['demail'] as $user){
        Mail::to($user)->send(new SendEmail($data));
    }

    return redirect()->back()->with('status','Invitation sent to users');

}

Email Template (email_invite_template.php)

    @component('mail::message')
    
    <p>Hi, {{ $data['dname'] }}</p>
    <p>You have just been invited to an event below is your invitation code:</p>
    <p></b>{{ $data['demail'] }}</b></p>
    
    Thanks,<br>
    {{ config('app.name') }}

@endcomponent

Thanks

Advertisement

Answer

You can’t just pass forward $data on every iteration. You need to construct your own array containing each name and email pair:

$data = [
  'dname' => $request->iname,
  'demail' => $request->iemail
];
// dname: `[0 => 'Mike', 1 => 'Bob', ...]
// demail: `[0 => 'mike@test.com', 1 => 'bob@test.com', ...]

foreach($data['demail'] as $index => $email){
  Mail::to($email)->send(new SendEmail([
    'dname' => $data['dname'][$index],
    'demail' => $email
  ]));
}

Now, you’re sending an array with 2 elements, dname and demail, each representing a pair of array elements:

// 1st Iteration: ['dname' => 'Mike', 'demail' => 'mike@test.com']
// 2nd Iteration: ['dname' => 'Bob', 'demail' => 'bob@test.com']

This is 100% dependant on you entering the same number of dname and demail values into your input though. If you have 3 emails, but only 2 names, this won’t work.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement