Laravel
Events
Minimize the number of traits
By default, Laravel adds several traits to a new Event class, even if they are not needed in your particular case. It’s still better to control traits more explicitly.
- use Dispatchable, InteractsWithSockets, SerializesModels;
+ use SerializesModels; // only if the Event will be used with Queued Event Listeners
Explanation:
Dispatchableadds static methods to simplify event dispatching, likeYourEvent::dispatch(). We do not use this syntax, so we don’t need this trait. Please use\Illuminate\Support\Facades\Eventfacade instead, e.g.Event::dispatch(new YourEvent()).SerializesModelsgracefully serializes any Eloquent models when the event object contains Eloquent models and is going to be serialized using PHP's serialize function, such as when using queued listeners.InteractsWithSocketsis for broadcasting only, e.g. when 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 class should be
final readonly
