Search code examples
phplaravellaravel-5.8laravel-events

Undefined property: App\Events\UserWalletNewTransaction::$user_id


I have created an Event called UserWalletNewTransaction.php and added this to it:

public $transaction;

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

And also registered it at EventServiceProivder.php:

use App\Listeners\UserWalletNotification;

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

Now in order to fire this event at the Controller, I coded this:

$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));

Then at the listener, UserWalletNotification.php, I tried:

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

But I get Undefined property: App\Events\UserWalletNewTransaction::$user_id error message.

However, if I try dd($event), this result successfully come up:

enter image description here

So what's going wrong here? How can I get the user_id that already exists at $event?

I would really appreciate any idea or suggestion from you guys...


Solution

  • The error is pretty clear, you are trying to access $user_id on an object that is App\Events\UserWalletNewTransaction and not your UserWalletTransaction model.

    Your fix is:

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

    If you use a good IDE, this would never happen to you, as it would already tell you that $event is UserWalletNewTransaction. Try using another IDE or one that can autocomplete that, so you can develop faster and better.