通知中的Laravel未定义变量
我正在用拉威尔做实验,我看到了这篇文章。 我完全遵循了它,但由于某种原因,在Notification类中发送邮件时,他找不到我在构造函数中声明的$user变量。当在构造函数中打印它时,它可以正常工作,这样就可以正确地传递用户对象,但是当我想在toMail方法中访问它时,出于某种原因,它是不可抗拒的。有人知道为什么以及如何解决这个问题吗通知中的Laravel未定义变量,laravel,Laravel,我正在用拉威尔做实验,我看到了这篇文章。 我完全遵循了它,但由于某种原因,在Notification类中发送邮件时,他找不到我在构造函数中声明的$user变量。当在构造函数中打印它时,它可以正常工作,这样就可以正确地传递用户对象,但是当我想在toMail方法中访问它时,出于某种原因,它是不可抗拒的。有人知道为什么以及如何解决这个问题吗 <?php namespace App\Notifications; use App\User; use Illuminate\Bus\Queueabl
<?php
namespace App\Notifications;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class UserRegisteredSuccessfully extends Notification
{
use Queueable;
/**
* @var User
*/
protected $user;
/**
* Create a new notification instance.
*
* @param User $user
*/
public function __construct(User $user)
{
$this->$user = $user;
// printing here works
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
// ERROR HERE (Undefined variable: user)
$user = $this->$user;
return (new MailMessage)
->subject('Succesfully created new account')
->greeting(sprintf('Hello %s', $user->username))
->line('You have successfully registered to our system. Please activate your account.')
->action('Click here', route('activate.user', $user->activation_code))
->line('Thank you for using our application!');
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
提前谢谢 您输入了两个错误:
在构造函数中:
$this->$user = $user;
应该是:
$this->user = $user;
$user = $this->user;
在toMail()
方法中:
$user = $this->$user;
应该是:
$this->user = $user;
$user = $this->user;
它不起作用的原因是,您当前正在使用
$user
的值作为变量名,并且您没有将用户对象的值分配给$this->user。我200%相信是$this->$用户;laravel是新手,自从我使用PHP以来已经很长时间了。同时感谢和抱歉!