2

I am developing a web application using Laravel framework. I am trying to trying to use event and listener in my application. But the event was trigged and the listener for the trigged event is not fired.

This is my controller action

    public function store(Request $request)
    {

        //other code
        $item = Item::create($request->all())
        broadcast(new ItemCreated($item));
        return "Item created successfully";
    }

This is my Events\ItemCreated.php

class ItemCreated
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $item;

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

Then I have a listener for that event.

Listeners/EmailSubscribedUsers.php

class EmailSubscribedUsers
{

    public function __construct()
    {
        //this constructor is not triggered
    }


    public function handle(ItemCreated $event)
    {
        //This method is not fired
    } 
}

In the EventServiceProvider I registered the event and the listener like this

protected $listen = [

    ItemCreated::class => [
        EmailSubscribedUsers::class
    ]
];

The event is trigged. But the listener is not fired. Why? What is wrong?

I tried the following solutions.

php artisan optimize
composer dumpautoload
php artisan clear-compiled
halfer
  • 19,824
  • 17
  • 99
  • 186
Wai Yan Hein
  • 13,651
  • 35
  • 180
  • 372

2 Answers2

5

Sorry everyone. The issue was I was unit testing. In the unit testing if I used Event::fake(), the event listeners are not triggered. I wanted to tested the logic in the event listeners. Therefore, I removed the Event::fake() and tested the logic in the listener instead.

Wai Yan Hein
  • 13,651
  • 35
  • 180
  • 372
4

First of all as pointed in comments use

event(new ItemCreated($item)); 

and not

broadcast(new ItemCreated($item));

In addition make sure you have set QUEUE_CONNECTION to sync in your .env file. If you used some other connection (for example database or Redis) make sure you run in console command:

php artisan queue:work

The last thing - verify your error log in storage/logs directory. You might have some other errors (for example missing import) and that's why your listener fails.

Also make sure in EventServiceProvider that you use valid classes and imported valid namespaces - otherwise listener won't be triggered.

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291