Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my event listener not firing in laravel 5?

So I am trying to log something simple when a new order is created in the laravel 5 application I am working on.

So I have a OrderWasCreated event which looks like so:

<?php

namespace App\Events;

use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

use App\Order;

class OrderWasCreated extends Event
{
    use SerializesModels;

    public $order;

    /**
     * OrderWasCreated constructor.
     */
    public function __construct(Order $order)
    {
        $this->order = $order;
    }


    /**
     * Get the channels the event should be broadcast on.
     *
     * @return array
     */
    public function broadcastOn()
    {
        return [];
    }
}

And then I have OrderEventListener which looks like so:

<?php

namespace App\Listeners;

use App\Events\OrderWasCreated;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class OrderEventListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    public function subscribe(Dispatcher $events)
    {
        $events->listen(
            'App\Events\OrderWasCreated',
            'App\Listeners\OrderEventListener@onOrderWasCreated'
        );
    }

    /**
     * Handle the event.
     *
     * @param  OrderWasCreated  $event
     * @return void
     */
    public function onOrderWasCreated(OrderWasCreated $event)
    {
        \Log::info('Order was created event fired');
    }
}

In my OrderController, I have this in my store method somewhere:

    event(new OrderWasCreated($order));

Yet, when I am creating new orders, I don't see anything in my log file. What am I missing?

like image 796
Rohan Avatar asked Sep 26 '22 20:09

Rohan


1 Answers

Probably you haven't added OrderEventListener into subscribe property of EventServiceProvider, it should look like this:

protected $subscribe = [
   'App\Listeners\OrderEventListener',
];

If you added, please run php artisan clear-compiled to make sure your app uses current version of classes.

like image 190
Marcin Nabiałek Avatar answered Sep 29 '22 01:09

Marcin Nabiałek