Reputation: 1207
I call an event this way:
event(new NewsLetterActivation($user));
and in event:
public $user;
public function __construct(User $user)
{
$this->user = $user;
}
It works.
Now In sometimes, I have an extra string variable and also may I did not have an $user ($user is empty or null).
How can I call it?
I try this:
event(new NewsLetterActivation(null,'[email protected]'));
and in event:
public function __construct(User $user,$email=null)
{
$this->user = $user;
$this->email= $email;
}
error:
Type error: Argument 1 passed to App\Events\NewsLetterActivation::__construct() must be an instance of App\Events\User, null given
Upvotes: 4
Views: 7156
Reputation: 1391
In __construct()
method or Listener you must change input parameter:
public function __construct(array $arg)
{
if (isset($agr['user])) {
$this->user = $agr['user];
}
if (isset($arg['email'])) {
$this->email= $agr['email'];
}
}
Then you can call event by different ways:
event(new NewsLetterActivation(['email'=>'[email protected]']);
event(new NewsLetterActivation(['email'=>'[email protected]', 'user'=>$user]);
event(new NewsLetterActivation(['user'=>$user]);
event(new NewsLetterActivation([]);
Upvotes: 2
Reputation: 9853
Change your controller to the following-
public function __construct($user,$email=null)
{
$this->user = $user;
$this->email= $email;
}
Upvotes: 2
Reputation: 163748
Since PHP 7.1 you can do this to be able to pass null
:
public function __construct(?User $user)
Upvotes: 3