user9277271
user9277271

Reputation:

Laravel 5.8: How to pass two arguements to Event & Listener

I'm using Laravel 5.8 and I have created an Event called UserWalletNewTransaction that goes like this:

public $transaction;
public $added_type;

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

As you can see I have specified two parameters here and these parameters are getting their value from the Controller:

event(new UserWalletNewTransaction($newTransaction, $value_added_type));

And then the Listener which is named UserWalletNotification goes like this:

public function handle(UserWalletNewTransaction $event, $added_type) {

But there is something wrong here, since I'm getting this error:

Too few arguments to function App\Listeners\UserWalletNotification::handle(), 1 passed and exactly 2 expected

So how to fix this issue? How can I pass two parameters to Event & Listener properly?


Update 1

Error Screenshot:

enter image description here

Upvotes: 3

Views: 3211

Answers (2)

Nidecker
Nidecker

Reputation: 190

UserWalletNewTransaction event:

public $transaction;
public $added_type;

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

which you can call like this event(new UserWalletNewTransaction($newTransaction, $value_added_type));

and UserWalletNotification listener:

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

Upvotes: 9

Hoto Cocoa
Hoto Cocoa

Reputation: 517

You can use array.

event(new UserWalletNewTransaction([ 'transaction' => $newTransaction, 'added_type' => $value_added_type));
public $transaction;
public $added_type;

public function __construct($data)
{
    $this->transaction = $data['transaction'];
    $this->added_type = $data['added_type'];
}

UPDATE #1:

You should remove 2nd argument of handle function. You can access added_type data in $event variable.

Upvotes: 0

Related Questions