Search code examples
phplaravellaravel-5.3

Using form request data in Laravel 5.3 mailable views


Looking around I cant find much information on how to do this. Plenty of the same examples just explaining the basic implementation of the mailable class but thats it.

I am sending an email from a contact form and have a route set up for testing that my form posts to:

Route::post('/sendmail', function() {    
    Mail::to("my email.com")->send(new MyTestMail());
});

I then have my mailable class which I have passed a test variable as a test string to:

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class MyTestMail extends Mailable
{
    use Queueable, SerializesModels;

    public $test;

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

    /**
    * Build the message.
    *
    * @return $this
    */
    public function build()
    {
        return $this->view('emails.myTestMail');
    }
}

What I wish to do is have access to my post values from the contact from and use them in the email view.


Solution

  • You can try passing the data you need to the constructor of that mailable.

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

    Now 'postdata' will be available to your view.

    Mail::to("my email.com")->send(new MyTestMail($request->all()))