DRY
Once upon a time, a noob developer like me wanted to write magnificent code. Inspired by the great programmers before me, I followed every coding principle religiously. When I discovered the DRY (Don't Repeat Yourself) principle, I vowed that my code would be as DRY as the desert. This led to many, many problems. I realized that principles should be understood deeply, not just followed blindly. Let’s explore what DRY means, when to use it, and when to ignore it.
The DRY principle, first introduced in The Pragmatic Programmer, states:
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
What is Knowledge Duplication?
Knowledge in software can be:
A precise functionality in the business domain.
An algorithm or complex logic.
Understanding DRY Principle
DRY is about avoiding knowledge duplication, not just avoiding code duplication.
Business logic should have a single, authoritative representation.
Unnecessary coupling and complexity can result from over-applying DRY.

Laravel Best Practices Applying DRY
Use Eloquent Models for Database Queries
✅ Encapsulate common queries in model methods instead of repeating
DB::table()queries everywhere.

Use Form Request Validation
✅ Move validation rules into a
FormRequestclass instead of writing them in controllers.

Use Blade Components for Reusability
✅ Create reusable components for UI elements (e.g., alerts) instead of copy-pasting code in multiple views.

Use Service Classes for Business Logic
✅ Extract business logic from controllers into separate service classes (e.g.,
UserService).

Use Repository Pattern for Data Access
✅ Create repositories to abstract database queries, making code more maintainable.

Use Config Files for Constants
✅ Store constants in Laravel’s
configfiles instead of hardcoding values.

Use Jobs for Background Processing
✅ Move heavy tasks (e.g., sending emails) to Laravel Jobs instead of running them directly in controllers.

Use Middleware for Repetitive Logic
✅ Apply middleware to handle repetitive logic (e.g., role-based access control) instead of checking in multiple controllers.

References
Last updated