Laravel中的条件广播

Is there an easy way to conditionally broadcast when using implement ShouldBroadcast on events? For example:

/**
 * Get the channels the event should be broadcast on.
 *
 * @return array
 */
public function broadcastOn()
{
    if ($x == 2) return;
    return ['test_channel'];
}

Unfortunately the code above still creates queued job, it does not succeed and continues to attempt it but cannot because it does not have a channel name. Is there an easy way to suppress the job being created with $x == 2?

The broadcastOn function must return an array.

So just return an empty array if you don't want to broadcast on any channels.

if ($x == 2) return [];

Just adding to this as Laravel now has support for a broadcastWhen() method on the event which covers this scenario.

e.g;

// on an event class...
public function broadcastWhen(){
    // check for whatever here
    return $bool;
}