7

I have created Mailable Class in Laravel 5.3 which calls the view. However, I need to pass some variables from my Controller to the Mailable Class and then use these values inside the View. This is my set-up:

Controller:

$mailData = array(
                   'userId'     => $result['user_id'],
                   'action'     => $result['user_action'],
                   'object'     => $result['user_object'],
                  );
Mail::send(new Notification($mailData));

Mailable:

class Notification extends Mailable
{
    use Queueable, SerializesModels;

    protected $mailData;

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

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        // Array for Blade
        $input = array(
                          'action'     => $mailData['action'],
                          'object'     => $mailData['object'],
                      );

        return $this->view('emails.notification')
                    ->with([
                        'inputs' => $this->input,
                      ]);
    }
}

The above gives me the error:

ErrorException in Notification.php line 25:
Array to string conversion

Referring to the construct line in Mailable Class:

$this->$mailData = $mailData;

What have I got wrong here? How do I correctly pass array values from Controller to Mailable and then use with to pass them on to the View?

Neel
  • 8,044
  • 21
  • 75
  • 119

1 Answers1

12

Try this:

public $mailData;

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

public function build()
{
    // Array for Blade
    $input = array(
                      'action'     => $this->mailData['action'],
                      'object'     => $this->mailData['object'],
                  );

    return $this->view('emails.notification')
                ->with([
                    'inputs' => $input,
                  ]);
}

Docs

Rimon Khan
  • 2,219
  • 1
  • 12
  • 17
  • Still getting the error `Array to string conversion` for this line: `$this->mailData = $mailData;` – Neel Nov 17 '16 at 11:49
  • 2
    Hi Rimon, I got it working. I had a typo in my code. Instead of `$this->mailData = $mailData;`, I had it as `$this->$mailData = $mailData;`. Secondly, having `protected` instead of `public` wasn't an issue. However, I need to update the references to `$this->mailData['xyz']` instead of `$mailData['xyz']`. Thank you for your help. Much appreciated.. – Neel Nov 17 '16 at 12:03
  • @Neel how do you call them in your view file? please help – Dmitry Malys Aug 05 '17 at 10:40
  • are you sure you need to pass values with `with` after you have already defined `public` at top? – VijayRana Dec 18 '17 at 07:31