【问题标题】:Laravel 5.5 Notification Set Null in database数据库中的 Laravel 5.5 通知集 Null
【发布时间】:2019-09-19 11:59:32
【问题描述】:

我正在尝试为用户设置通知。但是当我的方法尝试在我的 RequestinfoController 中将数据设置到数据库中时,它总是发送 null:user_id 有值

Xampp PHP 版本 7.2.5 阿帕奇/2.4.33 Laravel 5.5

/* Controller */
 public function acceptRequest($employer_id, $user_id)
  {
      $requestinfo = Requestinfo::where(['employer_id'=> $employer_id, 'user_id'=>$user_id])->first();
      $employer = Employer::find($employer_id);

          $requestinfo->update(['accepted'=> 1]);
          if($requestinfo){
            $employer->notify(new AcceptedRequest($user_id));

            return alert_msg('success', 'update_success' ,'requestinfo');
          }
      return alert_msg('error', 'update_error' ,'requestinfo');
  }

这是通知代码

/* Notification */
class AcceptedRequest extends Notification
{
    use Queueable;
    public $user_id;

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

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['database'];
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            "user_id"=> $this->user_id,
            "message"=> "request info accepted",
            "icon"=> "<i class='fas fa-check-square'></i>"
        ];
    }
}

//结果在数据库中

{"user_id":null,"message":"已接受请求信息","icon":""}

【问题讨论】:

    标签: laravel notifications laravel-5.5


    【解决方案1】:

    默认情况下,当您初始化对象时,变量设置为空。这就是为什么您将null 设为user_id。而真正的问题在于构造方法——

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

    我们不访问$前面的对象变量,您需要将其更改为$this-&gt;user_id = $user_id;

    $this-&gt;$user_id 基本上是在实例化一个双变量,这意味着$user_id 的值变成了一个变量。

    所以如果$user_id 的值是10,那么$this-&gt;$user_id 的结果是$this-&gt;10,这没有任何意义。

    但是,如果值是 dummy_value,则 $this-&gt;$user_id 会导致 $this-&gt;dummy_value,并且可能有一个名为 dummy_user 的对象变量。

    如果使用得当,双变量是一个非常强大的功能。

    【讨论】:

      猜你喜欢
      • 2018-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-16
      • 1970-01-01
      • 2018-09-01
      相关资源
      最近更新 更多