I am trying to add multiple listeners on an event in Laravel 12 which is something like this:
AppServiceProvider.php
use App\Events\Frontend\OTPVerificationEvent;
use App\Listeners\Frontend\{OTPOnMobileListener, OTPOnWhatsappListener};
class AppServiceProvider extends ServiceProvider {
...
/**
* Bootstrap any application services.
*/
public function boot(): void {
Event::listen(OTPVerificationEvent::class, [
[new OTPOnMobileListener, 'handle'],
[new OTPOnWhatsappListener, 'handle'],
]);
// --- OR ---
Event::listen(OTPVerificationEvent::class, [
new OTPOnMobileListener,
new OTPOnWhatsappListener,
]);
// --- OR ---
Event::listen(OTPVerificationEvent::class, [
OTPOnMobileListener::class,
OTPOnWhatsappListener::class,
]);
}
}
Events/Frontend/OTPVerificationEvent.php
class OTPVerificationEvent {
/**
* Public variables
*/
public $mobile;
public $mobileOtp;
public $whatsappOtp;
/**
* Create a new event instance.
*/
public function __construct($mobile, $mobileOtp, $whatsappOtp) {
$this->mobile = $mobile;
$this->mobileOtp = $mobileOtp;
$this->whatsappOtp = $whatsappOtp;
}
/**
* Get the channels the event should broadcast on.
*
* @return array<int, \Illuminate\Broadcasting\Channel>
*/
public function broadcastOn(): array {
return [
// new PrivateChannel('channel-name'),
];
}
}
Listeners/Frontend/OTPOnMobileListener.php
class OTPOnMobileListener {
/**
* Handle the event.
*/
public function handle(object $event): void {
echo "<pre>";
print_r($event);
echo "</pre>\n";
exit;
}
}
Listeners/Frontend/OTPOnWhatsappListener.php
class OTPOnWhatsappListener {
/**
* Handle the event.
*/
public function handle(object $event): void {
echo "<pre>";
print_r($event);
echo "</pre>\n";
exit;
}
}
I am keep getting this error:
First array member is not a valid class name or object
/* @method static void listen( \Illuminate\Events\QueuedClosure|callable|array|string $events, \Illuminate\Events\QueuedClosure|callable|array|string|null $listener = null ) */ class Event extends Facade {/* ... */}
Although the listener
method does accept an array
as its second parameter, you would only use that approach if you need to specify a custom function name to be called (the default being handle
). This is actually what you did in your first example, which works correctly in this case:
Event::listen(
OTPVerificationEvent::class,
[new OTPOnMobileListener, 'handle']
]);
Event::listen(
OTPVerificationEvent::class,
[new OTPOnWhatsappListener, 'handle']
]);