Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.4 Mail, passing data

Tags:

email

laravel

I'm trying to send an email to myself with a simple contact form in Laravel 5.4.

My form is 4 inputs: Nom, prenom, email and message. I just want to send an email with data in my mail template

This is my controller:

$this->validate($request, [
    'nom' => 'required|alpha',
    'prenom' => 'required|alpha',
    'email' => 'required|email',
    'message' => 'required',
    ]);

    $data = [
      'nom' => $request->nom,
      'prenom' => $request->prenom,
      'email' => $request->email,
      'message' => $request->message,
    ];

    Mail::to('myadress')->send(new Contact($data));

This is my "Contact" Mail:

public $data;

public function __construct($data)
{
    $this->nom = $data['nom'];
    $this->prenom = $data['prenom'];
    $this->email = $data['email'];
    $this->message = $data['message'];
}

/**
 * Build the message.
 *
 * @return $this
 */
public function build()
{
    return $this->view('emails.hello')->with([
                'nom' => $this->nom,
                'prenom' => $this->prenom,
                'email' => $this->email,
                'message' => $this->message,
            ]);
}

And this is my mail template:

<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="utf-8">
</head>
<body>
<h2>Demande d'informations </h2>

<div>
    <p>
      Vous recevez ce mail via le formulaire de contact du site .
    </p>
    <p>
      Adresse mail du contact: {{ $email }}
    </p>
    <p>
      Nom: {{ $nom }} / Prénom: {{ $prenom }}
    </p>
    <h3>Message du contact:</h3>
    <p>
      {{ $message }}
    </p>
</div>

</body>
</html>

I get an error message saying I can't pass an object as string. Thank for your help, it's the first time I use Laravel Mail

like image 805
Znne Avatar asked Mar 07 '17 11:03

Znne


People also ask

How do you pass data into an email template in laravel?

Laravel will pass all public properties of the mailable class to the email view. Mail::to($sendto)->send(new SendSBTorecipient($sb)); then in SendSBTorecipient add the SB to the constructor.

How do I know if an email was successful in laravel?

You can use the Mail::failures() function for that.

Can we use PHP Mail function in laravel?

Laravel provides drivers for SMTP, Mailgun, Mandrill, SparkPost, Amazon SES, PHP's mail function, and sendmail , allowing you to quickly get started sending mail through a local or cloud based service of your choice.


1 Answers

So, I found my problem:

public function __construct($data) {
    $this->data = $data;
}

And then:

public function build() {
    return $this->from('mailadress@blabla', 'my site')
    ->subject('hello you')
    ->view('emails.hello')->with(['data', $this->data]);
}

In my blade file:

Adresse mail du contact: {{ $data['email'] }}

Just because I tried to display an array as object in my view...

So my bad !

like image 65
Znne Avatar answered Oct 24 '22 07:10

Znne