Laravel Mail没有传递公共变量来查看

时间:2019-02-19 05:12:24

标签: php laravel

我想在Laravel中将字符串传递到电子邮件中,但是查看电子邮件时未显示该字符串。

$recoveryString被传递到邮件中:

$recoveryString = str_random(128);

$recoveryString = urlencode($recoveryString);   

RecoveryToken::where('user_id', $user->id)->delete();

$recoveryToken = RecoveryToken::create([
    'user_id' => $user->id,
    'recovery_token' => bcrypt($recoveryString),
]);         


Mail::to($user)->send(new ForgotEmail($user, $recoveryString));

ForgotEmail.php

<?php

namespace App\Mail;

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

class ForgotEmail extends Mailable
{
    use Queueable, SerializesModels;


    public $user;
    public $recoveryString;



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



    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->from('noreply@mainchan.com')
                ->view('emails.forgot');
    }
}

在我的电子邮件刀片模板中,{{ $user->username }}将检索正确的数据,但是{{ $recoveryString }}将为空白。为什么会这样呢?我的印象是,您可邮递类上定义的任何公共属性都将自动提供给视图。

2 个答案:

答案 0 :(得分:3)

错别字-我自己做了100次:

在构造函数中,请记住使用$this

$recoveryString = $recoveryString;变为$this->recoveryString = $recoveryString;

HTH

答案 1 :(得分:1)

您的构造函数应具有$this->recoveryString而不是$recoveryString

应该是:

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