【问题标题】:ErrorException Undefined variable $dataErrorException 未定义变量 $data
【发布时间】:2021-02-12 12:28:27
【问题描述】:

在数据库通知中,我想向特定用户发送通知

但在构造函数中,$data显示为未定义

这里Employee是我的模型名,我想通知员工表中的员工id为1,数据将插入到员工中

$data=Employee::create([
        'first_name'=>$request->input('first_name'),
        'last_name'=>$request->input('last_name'),
        'username'=>$request->input('username'),
        'email'=>$request->input('email'),
        'password'=>$request->input('password'),
        'confirm_password'=>$request->input('confirm_password'),
    ]);
    

    $admin=Employee::find(1);
    
    $admin->notify(new NotifyAdmin($data));

通知类

   <?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Notifiable;
use App\Models\Employee; 


class NotifyAdmin extends Notification implements ShouldQueue
{
    use Queueable, Notifiable;
    private $val;

   
    public function __construct(Employee $employee)
    {
       
        $this->val=$data;
    }

    public function via($notifiable)
    {
        return ['database'];
    }

   
    public function toArray($notifiable)
    {
        return [
            'username'=> $this->val->username
        ];
    }
}

【问题讨论】:

  • 您的 $data 作为参数传递,但您的构造函数定义了 $employee 参数。因此 $this->val = $employee;应该工作。
  • 如果我使用 $employee 它会显示 BadMethodCallException 调用未定义的方法 App\Models\Employee::notify()

标签: laravel


【解决方案1】:

你的问题是因为你在构造函数参数中写了 $employee 但是你使用了 data ,所以 data 不存在,把它改成这样:-

   public function __construct(Employee $employee)
    {
       
        $this->val=$employee;
    }

【讨论】:

  • 显示此错误 BadMethodCallException Call to undefined method App\Models\Employee::notify()
  • 你在你的模型中使用了 Notifiable trait 吗?
  • 我的模型是员工,没有可通知的特征。这个我不熟悉,不知道怎么用?
  • 要让你的模型收听通知,你应该在你的模型上使用 Notifiable trait,如下所示:- laravel.com/docs/8.x/notifications#using-the-notifiable-trait
  • ............哇,它有效。太感谢了。你知道我已经花了 2 天时间来解决这个问题。但我没有。现在它解决了。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 2018-01-26
  • 2020-09-24
  • 2018-11-29
  • 2020-04-16
  • 1970-01-01
相关资源
最近更新 更多