𝗠𝗮𝘀𝘁𝗲𝗿𝗶𝗻𝗴 𝗘𝘃𝗲𝗻𝘁-𝗗𝗿𝗶𝘃𝗲𝗻 𝗗𝗲𝗰𝗼𝘂𝗽𝗹𝗶𝗻𝗴 𝗶𝗻 𝗟𝗮𝗿𝗮𝘃𝗲𝗹

Your Laravel controllers often become dumping grounds for business logic.

You start with a simple registration flow. Soon, you add email notifications, Slack alerts, audit logs, and API calls to one single method. This creates a fat controller.

Fat controllers make your code fragile. They are hard to test. They break the Single Responsibility Principle.

You do not need complex tools like RabbitMQ to fix this. Laravel has a built-in event system that works for most needs.

The problem with tight coupling: If a newsletter API is slow, your user registration slows down. If a mail service fails, the entire request fails.

The solution: Event-Driven Architecture.

Events act as a middle layer. Your controller announces an action. Listeners react to that action independently.

A lean controller looks like this:

public function register(RegisterRequest $request) { $user = User::create($request->validated());

UserRegistered::dispatch($user);

return response()->json(['message' => 'Success'], 201);

}

The controller now only handles data persistence. It does not care about side effects.

You gain three major benefits:

  • Performance: Users get a response immediately. Heavy tasks run in the background using the ShouldQueue interface.
  • Resilience: If a service is down, the listener can retry the task without breaking the main application.
  • Extensibility: You can add new features, like push notifications, by adding a new listener. You do not touch the original controller.

Best practices to follow:

  • Focus on side effects: Use events for post-processing. Do not use them for core logic that must happen instantly.
  • Use descriptive names: Use past-tense names like OrderPlaced or UserRegistered. This shows the action already happened.
  • Avoid over-abstraction: If a piece of code is simple and used in one place, a function call is better than an event.

Use Eloquent Observers for database changes. Use Events for business actions.

Refactoring to events is about durability. It makes your code easier to debug and faster to test.

Pick one noisy side effect in your controller and move it to a listener today.

Try this sandbox example: https://onlinephp.io/c/1f7b2

ماخذ: https://dev.to/codecraft_diary_3d13677fb/beyond-fat-controllers-mastering-event-driven-decoupling-in-laravel-2dd6