Laravel - Events - Queuable Anonymous Event Listeners
When registering closure based event listeners manually, you may wrap the listener closure within the Illuminate\Events\queueable
function to instruct Laravel to execute the listener using the queue:
use App\Events\PodcastProcessed;
use function Illuminate\Events\queueable;
use Illuminate\Support\Facades\Event;
/**
* Register any other events for your application.
*
* @return void
*/
public function boot()
{
Event::listen(queueable(function (PodcastProcessed $event) {
//
}));
}
Like queued jobs, you may use the onConnection
, onQueue
, and delay
methods to customize the execution of the queued listener:
Event::listen(queueable(function (PodcastProcessed $event) {
//
})->onConnection('redis')->onQueue('podcasts')->delay(now()->addSeconds(10)));
If you would like to handle anonymous queued listener failures, you may provide a closure to the catch
method while defining the queueable
listener. This closure will receive the event instance and the Throwable
instance that caused the listener's failure:
use App\Events\PodcastProcessed;
use function Illuminate\Events\queueable;
use Illuminate\Support\Facades\Event;
use Throwable;
Event::listen(queueable(function (PodcastProcessed $event) {
//
})->catch(function (PodcastProcessed $event, Throwable $e) {
// The queued listener failed...
}));