【问题标题】:Undefined property: App\Events\UserWalletNewTransaction::$user_id未定义的属性:App\Events\UserWalletNewTransaction::$user_id
【发布时间】:2021-09-26 07:54:12
【问题描述】:

我创建了一个名为 UserWalletNewTransaction.php 的事件并将其添加到其中:

public $transaction;

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

并且还在EventServiceProivder.php注册了:

use App\Listeners\UserWalletNotification;

protected $listen = [
    UserWalletNewTransaction::class => [
        UserWalletNotification::class,
    ],

现在为了在控制器上触发这个事件,我编写了这样的代码:

$newTransaction = UserWalletTransaction::create(['user_id' => $user_id, 'wallet_id' => $wallet_id, 'creator_id' => $creator_id, 'amount' => $amount_add_value, 'description' => $trans_desc]);

event(new UserWalletNewTransaction($newTransaction));

然后在听者UserWalletNotification.php,我尝试了:

public function handle(UserWalletNewTransaction $event) {
    $uid = $event->user_id;
    dd($uid);
}

但我收到Undefined property: App\Events\UserWalletNewTransaction::$user_id 错误消息。

但是,如果我尝试dd($event),则成功出现此结果:

那么这里出了什么问题?如何获取$event 中已存在的user_id

非常感谢你们的任何想法或建议......

【问题讨论】:

    标签: php laravel laravel-5.8 laravel-events


    【解决方案1】:

    尝试关注,将其添加到您的事件类UserWalletNewTransaction

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

    在监听器中

    public function handle(UserWalletNewTransaction $event) {
        $uid = $event->transaction->user_id;
        dd($uid);
    }
    

    【讨论】:

    • 传递给 App\Events\UserWalletNewTransaction::__construct() 的参数 1 必须是 App\Events\UserWalletTransaction 的实例,给定 App\UserWalletTransaction 的实例,在 UserWalletController.php 中调用
    • 您必须在事件类的开头添加此代码use App\UserWalletTransaction;
    【解决方案2】:

    错误很明显,您正试图访问 $user_id 对象上的 App\Events\UserWalletNewTransaction 而不是您的 UserWalletTransaction 模型。

    您的解决方法是:

    public function handle(UserWalletNewTransaction $event) {
        $uid = $event->transaction->user_id;
    }
    

    如果您使用一个好的 IDE,这将永远不会发生在您身上,因为它已经告诉您 $eventUserWalletNewTransaction。尝试使用其他 IDE 或可以自动完成的 IDE,这样您就可以更快更好地开发。

    【讨论】:

    • Trying to get property 'user_id' of non-object
    • @loctoj 然后,您没有创建对象...UserWalletTransaction::create 没有返回对象,可能没有添加,我认为它返回了falsenull,作为您的原始图像显示...这是基本调试,请执行dd($event->transaction) 并向我们展示结果。
    • 如果答案是null,那么它没有创建对象,我想你可能没有在模型中定义一些东西作为$fillable属性。检查或创建一个新问题,因为我们的代码是正确的,但你现在有一个新问题。我还是要说你的图片里有一些数据,我真的很困惑。
    猜你喜欢
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 2020-01-24
    • 2018-09-13
    • 2021-01-30
    相关资源
    最近更新 更多