Sobes.tech
Junior — Middle

Have you used event-driven mechanisms in Laravel for event handling?

sobes.tech AI

Answer from AI

Yes, in Laravel I used the event mechanism to separate processing logic from the main code. For example, when a user registers, a UserRegistered event is triggered, which is listened to by a handler that sends a welcome email. This makes the code more modular and easier to maintain.

Example:

// Defining the event
class UserRegistered implements ShouldBroadcast
{
    public $user;
    public function __construct(User $user) {
        $this->user = $user;
    }
}

// Listener
class SendWelcomeEmail
{
    public function handle(UserRegistered $event) {
        Mail::to($event->user->email)->send(new WelcomeMail());
    }
}

// Triggering the event
event(new UserRegistered($user));
Have you used event-driven mechanisms in Laravel for… - sobes.tech