将数组参数从控制器传递到Mailable类。 Laravel

时间:2016-09-10 05:40:42

标签: php laravel laravel-5

我正在尝试在用户成功注册后发送电子邮件。所以现在我被困在电子邮件模板中传递数据。我正在发送电子邮件与Mailable。所以从我的注册控制器我使用Mail::to('example@email.com','User Name')->send(new Verify_Email()) 所以我的问题是如何将数组参数传递给new Verify_Email()按摩构建类。然后如何从 Verify_Email传递到视图

RegisterController.php

public function __construct()
{
    $this->middleware('guest');
}

/**
 * Get a validator for an incoming registration request.
 *
 * @param  array  $data
 * @return \Illuminate\Contracts\Validation\Validator
 */
protected function validator(array $data)
{
    return Validator::make($data, [
        'firstname' => 'required|max:255',
        'lastname' => 'required|max:255',
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|min:6|confirmed',
    ]);
}

/**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return User
 */
protected function create(array $data)
{
    $confirmation_code = str_random(30);
    $user =  User::create([
        'firstname' => $data['firstname'],
        'lastname' => $data['lastname'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        'confirmation_code' => $confirmation_code
    ]);
    $email_data = ([
       'name' => $data['firstname'].' '.$data['lastname'],
        'link' => '#'
    ]);
    Mail::to('example@email.com','User Name')->send(new Verify_Email());

    return $user;

}

Verify_Email.php

class Verify_Email extends Mailable
{
 use Queueable, SerializesModels;

/**
 * Create a new message instance.
 *
 * @return void
 */

public function __construct()
{
    //
}

/**
 * Build the message.
 *
 * @return $this
 */
public function build()
{
    return $this->from('example@example.com')
        ->view('emails.verify-user');
        //--------------------------> **Send data to view**
        //->with([            
            //'name' => $this->data->name,
            //'link' => $this->data->link
        //]); 
}

1 个答案:

答案 0 :(得分:12)

请遵循这种方法

将输入传递给 Verify_Email构造函数,并使用$ this->变量将它们传递到视图中。

Mail::to('example@email.com','User Name')->send(new Verify_Email($inputs))

然后在 Verify_Email

class Verify_Email extends Mailable {

  use Queueable, SerializesModels;

  protected $inputs;

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

  /**
   * Build the message.
   *
   * @return $this
   */
  public function build()
  {
    return $this->from('example@example.com')
                ->view('emails.verify-user')
                ->with([
                  'inputs' => $this->inputs,
                ]);
  }

}

希望能回答你的问题:)