DevPath
Mid lesson · 12 min

Keep controllers thin and HTTP errors clear

Separate transport concerns from decisions about business state.

Give each layer one job

A controller identifies the caller, validates input, invokes a service, and maps the outcome to an HTTP response. The service owns the business rule and can be tested without an HTTP request. The repository or model handles persistence. Moving lines into a service is useful only when the resulting boundary is clearer.

Map expected conflicts

A domain rule such as 'this slot is already booked' is not an unexpected server failure. Model it as a named conflict and return a stable 409 response with a safe message. Keep unexpected exceptions visible to monitoring while avoiding stack traces in responses.

try {
    $booking = $bookings->reserve($command);
} catch (SlotUnavailable $e) {
    return response()->json(['error' => 'slot_unavailable'], 409);
}

Test through the public seam

A feature test should assert status, response shape, and database effect for success and conflict. A unit test can probe detailed service rules. Avoid asserting that a controller called a specific private helper; that locks the test to implementation while missing the contract a client sees.

Check your understanding

When should a booking conflict become HTTP 409 instead of 500?

Show explanation

When it is an expected business outcome. Reserve 500 for unexpected failures that need investigation.

Put this lesson into practice

A practice activity at this level in the same module.

Try: Extract business logic from a fat controller

Further reading

Primary references for this module. Check the current version when behavior or framework guidance may have changed.