Skip to content

Event

Minimize the number of traits

By default, Laravel adds few traits to a new Event class, even if it’s not needed in your particular case. We fixed it in our custom stub file for Event, but it’s still better to control traits more explicitly.

diff
-use Dispatchable, InteractsWithSockets, SerializesModels;
+use SerializesModels; // only if the Event will be used with Queued Event Listeners
  • Dispatchable is to add static methods to simplify event dispatching, like YourEvent::dispatch(). We do not use this syntax, so we don’t need this trait. Please use \Illuminate\Support\Facades\Event facade instead, e.g. Event::dispatch(new YourEvent()).
  • SerializesModels is to gracefully serialize any Eloquent models if the event object contains Eloquent models and going to be serialized using PHP's serialize function, such as when utilizing queued listeners.
  • InteractsWithSockets is for broadcasting only, e.g. using Laravel Echo.

Best Practices:

  • Tailor Event class traits based on specific needs rather than using the default set.
  • Understand the implications of each trait to avoid unnecessary overhead or missing functionality.
  • Event classes should be final and readonly