-1

我创建了一个名为的事件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),这个结果会成功出现:

在此处输入图像描述

那么这里出了什么问题?我怎样才能得到user_id已经存在的那个$event

我真的很感激你们的任何想法或建议......

4

2 回答 2

1

尝试以下,将其添加到您的 Event 类中UserWalletNewTransaction

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

并在侦听器中

public function handle(UserWalletNewTransaction $event) {
    $uid = $event->transaction->user_id;
    dd($uid);
}
于 2021-07-18T08:07:22.510 回答
1

错误很明显,您正在尝试访问$user_id一个App\Events\UserWalletNewTransaction不是您的UserWalletTransaction模型的对象。

您的解决方法是:

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

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

于 2021-07-18T08:07:32.313 回答