LoginSignup
1
0

More than 1 year has passed since last update.

【Laravel】イベントとリスナーで設定した通知が2回くる問題の解決法

Posted at

環境

Laravel v9.5.1 (PHP v8.1.3)

状況

動作確認で通知を飛ばしたとき、同じ通知が2回飛んでしまっていた。

  • $listenの配列にPodcastProcessedイベントとSendPodcastNotificationリスナーを手動で登録
  • shouldDiscoverEvents()メソッドをデフォルトのfalseからtrueに変更
namespace App\Providers;

use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;

class EventServiceProvider extends ServiceProvider
{
    protected $listen = [
        //デフォルトで登録済みのイベントとリスナー
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
        PodcastProcessed::class => [
            SendPodcastNotification::class,
        ],
    ];

    public function shouldDiscoverEvents()
    {
        return true;
    }
}

解決法

  • 手動で登録する方のPodcastProcessedイベントとSendPodcastNotificationリスナーの記述を削除する。

イベントとリスナーの関連付けを手動と自動の両方で登録してしまっていたことが原因。

namespace App\Providers;

use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;

class EventServiceProvider extends ServiceProvider
{
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
    ];

    public function shouldDiscoverEvents()
    {
        return true;
    }
}

よく見たらドキュメントにちゃんと書いてある。

EventServiceProviderの$listen配列にイベントとリスナを手作業で登録する代わりに、自動イベント検出を有効にすることもできます。イベント検出が有効になっている場合、LaravelはアプリケーションのListenersディレクトリをスキャンすることでイベントとリスナを自動的に見つけて登録します。(略)
イベント検出はデフォルトで無効になっていますが、アプリケーションのEventServiceProviderのshouldDiscoverEventsメソッドをオーバーライドすることで有効にできます。

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0