Nienna
Nienna

Reputation: 453

Getting a call to undefined method in laravel when doing events

I'm getting this error when I do a post and it hits my event

Call to undefined method App\Events\UpdateProductCount::__invoke()

This is my code

    public function create()
    {
        $product = Product::create([
            'name' => request('name'),
            'description' => request('description'),
        ]);

        dispatch(new UpdateProductCount($product));
    }

This is what I have in my UpdateProductCount event

    <?php

    namespace App\Events;

    use App\Models\Product;
    use Illuminate\Broadcasting\Channel;
    use Illuminate\Broadcasting\InteractsWithSockets;
    use Illuminate\Broadcasting\PresenceChannel;
    use Illuminate\Broadcasting\PrivateChannel;
    use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
    use Illuminate\Foundation\Events\Dispatchable;
    use Illuminate\Queue\SerializesModels;

    class UpdateProductCount
    {
        use Dispatchable, InteractsWithSockets, SerializesModels;

        public Product $product;

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

        public function broadcastOn()
        {
            return new PrivateChannel('product-count-update'.$this->product);
        }
    }

and this is what I have in my UpdateProductCountListener

    <?php

    namespace App\Listeners;

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

    class UpdateProductCountListener
    {

        public function __construct()
        {
            
        }

        public function handle(UpdateProductCount $event)
        {
            dd($event);
        }
    }

Upvotes: 9

Views: 11721

Answers (3)

Supun Kavinda
Supun Kavinda

Reputation: 1493

My problem was importing the wrong Dispatchable trait.

wrong:

use Illuminate\Foundation\Bus\Dispatchable;

correct:

use Illuminate\Foundation\Events\Dispatchable;

Upvotes: 14

Nienna
Nienna

Reputation: 453

After looking at my stack trace like @miken32 suggested it was complaining about this line

dispatch(new UpdateProductCount($product));

so I tried changing dispatch to event

// dispatch(new UpdateProductCount($product)); 
event(new UpdateProductCount($product)); 

and that worked.

Upvotes: 19

saad
saad

Reputation: 21

prob in your EventServicesProvider you must have:

UpdateProductCount::class => [
      UpdateProductCountListener::class,
]

Upvotes: 1

Related Questions