1

I can't add constructor in my event listener.Laravel 11 there is no EventService provider also. I need an example for this

 public function handle(NewUserEvent $event): void
    {
        Mail::send('3_Emails.1_CommonMailTemplate', $mailData, function ($message) use ($Name, $Email) {
            $message->to($Email)
                ->subject("Contact | $Name")
                ->cc('[email protected]') // Add CC recipient
                ->bcc('[email protected]'); // Add BCC recipient
        });
    }
here i cant get $event in it.

3 Answers 3

2

It seems you have copied this part from somewhere. Before you come to this, there are a few things you need to do

  1. Create an event called NewUserEvent
  2. Dispatch the Event

In App\Events\NewUserEvent.php, if not, create one

namespace App\Events;

use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class NewUserEvent
{
    use Dispatchable, SerializesModels;

    public $name;
    public $email;

    public function __construct($name, $email)
    {
        $this->name = $name;
        $this->email = $email;
    }
}

In Controller, call the event.

event(new NewUserEvent($name, $email));

As I remember, Laravel 11 does not use EventServiceProvider; it is set to auto-discover event listeners. If not working, set it manually.

2

In Laravel 11 there isn't EventServiceProvider anymore.

You need to create:

  • event with php artisan make:event <eventName>
  • the relative listener with php artisan make:listener <listenerName> --event=eventName

Laravel scan app\Listeners directory and auto discover all Events associated with each Listener.

With this approach no need EventServiceProvider anymore.

More cleaner approach, imho.

At the end: you can dispatch the event from the controller (for example): EventName::dispatch()

1

Using the Event facade, you may manually register events and their corresponding listeners within the boot method of your application's AppServiceProvider

Event::listen(
    PodcastProcessed::class,
    SendPodcastNotification::class,
);

Not the answer you're looking for? Browse other questions tagged or ask your own question.