【问题标题】:Getting a call to undefined method in laravel when doing events在执行事件时调用 laravel 中未定义的方法
【发布时间】:2021-03-07 23:04:12
【问题描述】:

我在发布帖子时收到此错误,并且它触发了我的活动

调用未定义的方法 App\Events\UpdateProductCount::__invoke()

这是我的代码

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

        dispatch(new UpdateProductCount($product));
    }

这就是我的 UpdateProductCount 事件中的内容

    <?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);
        }
    }

这就是我的 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);
        }
    }

【问题讨论】:

  • 尝试运行composer update
  • 我试过了,还是一样的错误
  • 您的错误消息包括导致错误的行号和文件,以及完整的堆栈跟踪...

标签: laravel laravel-8


【解决方案1】:

在查看我的堆栈跟踪后,如 @miken32 建议它在抱怨这一行

dispatch(new UpdateProductCount($product));

所以我尝试将dispatch 更改为event

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

而且成功了。

【讨论】:

    【解决方案2】:

    你的 EventServicesProvider 中你必须有的概率:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-23
      • 1970-01-01
      • 2020-03-29
      • 2015-05-31
      • 2016-06-05
      • 2016-09-03
      • 2015-06-10
      • 2016-12-16
      相关资源
      最近更新 更多