pilat
434
5
Laravel

Can I cancel Event broadcasting from within the event class?

Posted 1 year ago by pilat

Hi, I have an event class to send notifications about external API sync status. It's quite simple, and I'm appending the code to the end of this post.

Now, I have one task: I'd only like to broadcast this event if the following conditions are both met:

  1. It's not Local environment;
  2. t is Http kernel, not Console (because the syncing can also be initiated as Artisan command or a scheduled task and there is no use for websockets in this case).

Now, I'm using something like this in my "client code" when firing the event:

        if (! App::environment('local')) {
            event(new SomethingWasSynced($this->subdomain, 'custom_fields', $this->cfsGeneratedCount));
        }

The problem: I have to remember to use this conditions every time I need to fire this event. Besides, it's not very dry this way.

So the question is: can I check this condition and cancel/abort broadcasting from within the event itself? For example, by returning false in constructor or calling some magic method, I don't know…

The second question is: how do I tell a web request (Http\Kernel) from a Console one (Console\Kernel)? Can I do it from within the event class as well?

class SomethingWasSynced implements ShouldBroadcast
{
    use InteractsWithSockets, SerializesModels;

    /**
     * The name of the queue on which to place the event.
     *
     * @var string
     */
    public $broadcastQueue = 'pusher';

    public $subdomain;
    public $what;
    public $totalCount;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($subdomain, $what, $totalCount)
    {
        $this->subdomain = $subdomain;
        $this->what = $what;
        $this->totalCount = $totalCount;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new Channel("syncing-{$this->subdomain}");
    }

    public function onQueue()
    {
        return 'pusher';
    }
}

Please sign in or create an account to participate in this conversation.