Laravel Clean Pattern — Universal Master Skill
A single, project-agnostic production architecture playbook for creating any new Laravel 12+ / PHP 8.3+ project (SaaS, E-Commerce, Marketplace, Booking, Fintech, Mobile/SPA API) or refactoring existing backends. Enforces SOLID principles, pragmatic Design Patterns, thin controllers, typed contracts, zero N+1 queries, full en/ar multi-language localization, Day-1 security hardening, AES-256-GCM response encryption, and automated Postman collections.
0. Creating Any New Laravel Project (Single-Module Architecture Bootstrap)
Whenever starting a brand-new Laravel project, split every business domain into its own self-contained single module under app/Modules/<ModuleName>/, and keep only cross-cutting infrastructure in app/Shared/:
- Scaffold & Guard:
- Initialize Laravel (
composer create-project laravel/laravel <project-name>). - Keep
.envout of Git, maintain placeholder-only.env.example, and enableModel::preventLazyLoading(! app()->isProduction())inAppServiceProvider::boot().
- Initialize Laravel (
- Create the Modular Folder Skeleton (
app/Shared/+app/Modules/<ModuleName>/):app/ ├── Shared/ # Cross-cutting infrastructure only (no business domain) │ ├── Http/ │ │ ├── Controllers/BaseController.php # Centralized ApiResponse JSON helpers │ │ └── Middleware/ # SetAppLocale, SecurityHeaders, EncryptBrowserResponses │ ├── Services/BrowserResponseCrypto.php # Shared AES-256-GCM transport crypto │ ├── Support/ApiResponse.php # Unified { success, message, data } builder │ └── ValueObjects/Money.php # Shared immutable Value Objects └── Modules/ └── <ModuleName>/ # e.g. Auth, Users, Catalog, Orders, Billing ├── Providers/<ModuleName>ServiceProvider.php # Binds contracts, routes, migrations, lang ├── Routes/api.php # Module-scoped routes (/api/v1/<module>) ├── Http/ │ ├── Controllers/ # Thin HTTP orchestrators only │ ├── Requests/ # FormRequests (prepareForValidation & toDto) │ └── Resources/ # Typed JsonResources (whenLoaded / whenCounted) ├── Actions/ # Multi-repository single-use invokable use cases ├── Data/ # Immutable final readonly DTOs ├── Enums/ # PHP 8.1+ Backed Enums with localized label() ├── Events/ # Domain events & PrivateChannel broadcasts ├── Listeners/ # Queued listeners reacting to other modules' events ├── Models/ # Eloquent models with explicit $fillable & casts() ├── Policies/ # Authorization & ownership (IDOR prevention) ├── Repositories/ │ ├── Contracts/ # Segregated *RepositoryInterface contracts │ └── *Repository.php # Eloquent queries, transactions & lockForUpdate ├── Services/ # Cohesive domain services (scoped caching, Strategy/Decorator) ├── Database/ │ ├── Migrations/ # Module-owned migrations (loaded by provider) │ └── Factories/ # Module model factories └── Lang/ ├── en/messages.php # Module EN translations (100% parity with ar) └── ar/messages.php # Module AR translations (100% parity with en) lang/ ├── en/messages.php # Shared/global EN messages └── ar/ # Shared/global AR messages & validation.php postman/ └── <project>.postman_collection.json # Auto-maintained v2.1.0 API collection - Plug-and-Play Insert / Eject Modules (Clean Repository Pattern):
- Auto-Discovery (
App\Shared\Providers\ModuleRegistryProvider): RegisterModuleRegistryProvideronce inbootstrap/providers.phpto auto-discover everyapp/Modules/<Module>/Providers/<Module>ServiceProvider.php(respectingconfig/modules.phpenable/disable toggles). - Self-Contained Module Ownership: Each
<Module>ServiceProviderowns 100% of itsRepositories/Contracts/*Interface→*Repositorybindings,Config/<module>.php(mergeConfigFrom),Policies(Gate::policy),Routes/api.php,Database/Migrations,Lang/{en,ar}(__('orders::messages.*')), andEvent::listen(...)subscriptions. Never edit global files to wire a module. - Zero-Friction Insert & Eject:
- Insert: Drop
app/Modules/<NewModule>/intoapp/Modules/→ repositories, routes, migrations, translations, policies, and listeners activate automatically. - Eject: Delete
app/Modules/<Module>/(or toggle itfalseinconfig/modules.php) → zero broken imports, routes, migrations, or DI bindings anywhere else in the app.
- Insert: Drop
- Zero Cross-Module Model Leaks: Module A NEVER queries Module B's Eloquent
Modeldirectly or adds hard DB foreign keys into an ejectable module's tables. Cross-module interaction goes ONLY through:- Shared Contracts + Null Object Fallback (
app/Shared/Contracts/*Interfacewith a safe no-op default bound inModuleRegistryProvider, overridden when the target module is inserted), OR - Domain Events + module-local queued
Listeners (Observer/Pub-Sub).
- Shared Contracts + Null Object Fallback (
- Blueprint: ModuleServiceProviderTemplate.php.
- Auto-Discovery (
- Wire Global Middleware & Day-1 Security:
- Register in
bootstrap/app.php:trustProxies(at: '*')→SetAppLocale→SecurityHeaders→ (optional)EncryptBrowserResponses. - Lock down
config/cors.php, secure session cookies,RateLimiterrules, Policies/ownership checks, upload validation, andcomposer audit(see Section 6).
- Register in
- Build & Verify: Build every feature inside its module with SOLID + Design Patterns + 5-Layer Clean Pattern +
en/artranslations + Postman collection updates + automated audits.
1. SOLID Principles & Design Patterns
Every Laravel feature, service, repository, and refactor MUST follow SOLID and select the right pattern without speculative over-abstraction:
SOLID in Laravel
- S — Single Responsibility (SRP): One reason to change per class —
FormRequest(normalize & validate),Controller(HTTP orchestration),Repository(persistence/queries/transactions),Service/Action(domain workflow),JsonResource(serialization). Never build "God" controllers, models, or services. - O — Open/Closed (OCP): Extend varying behaviors (payment gateways, pricing tiers, notification channels, exporters, filter pipelines) via interfaces + Strategy, Decorator, or Laravel
Pipelinebindings instead of growingif/elseiforswitchchains. - L — Liskov Substitution (LSP): Every implementation of a contract MUST honor parameter types, return types, nullability, and exceptions. Never branch on concrete types with
instanceofor throw "not supported" stubs. - I — Interface Segregation (ISP): Prefer small, role-focused contracts (e.g., splitting
ReaderInterface/WriterInterface) over fat multi-domain interfaces. - D — Dependency Inversion (DIP): High-level controllers and services depend on
Contracts\*Interfaceviaprivate readonlyconstructor promotion, bound inAppServiceProvider::register(). Avoid Service Locator (app(...)) inside domain logic.
Core Design Patterns Selection Matrix
| Scenario | Pattern | SOLID |
|---|---|---|
| Persistence & transactions | Repository (app/Repositories/Contracts/*Interface.php) |
SRP, DIP |
| Swappable algorithms/providers | Strategy + $this->app->tag([...]) Resolver |
OCP, DIP |
| Caching/logging around a repo | Decorator wrapping *Interface |
SRP, OCP |
| Multi-step filtering/checkout | Pipeline (Illuminate\Pipeline\Pipeline) |
SRP, OCP |
| Decoupled side effects | Observer / Events (DB::afterCommit + queued Job) |
SRP, OCP |
| Multi-repo single use case | Action (final readonly class in app/Actions/) |
SRP |
| Typed inputs & invariants | Readonly DTO (FormRequest::toDto()) & Value Object (Money) |
SRP, LSP |
| Fat interface with unused methods | Segregated Interfaces | ISP, LSP |
- Blueprint: StrategyAndDecoratorTemplate.php
2. 5-Layer Clean Architecture & Repository Pattern
Every backend feature flows through 5 strict layers:
- FormRequest (
app/Http/Requests/**) — Input normalization & validation. - Thin Controller (
app/Http/Controllers/**) — HTTP orchestration only. - Repository (
app/Repositories/Contracts/*Interface.php+app/Repositories/*Repository.php) — Persistence, eager loading, and locking. - Reusable Services & Actions (
app/Services/*Service.php,app/Actions/*Action.php) — Cohesive domain logic & caching. - API Resource & Response (
app/Http/Resources/*Resource.php+App\Support\ApiResponse) — Typed JSON contracts.
Repository Rules
- Bind every interface in
AppServiceProvider::register():$this->app->bind(DomainRepositoryInterface::class, DomainRepository::class);. - NEVER call
Model::query(),Model::where(),Model::find(),Model::create(),DB::transaction(), orSchema::hasTable()inside any controller. - Wrap multi-step state transitions in
DB::transaction(...)with->lockForUpdate()inside the repository and return structured results (['code' => 200, 'model' => $m]or['code' => 422, 'message' => __('messages.*')]). - Blueprint: RepositoryTemplate.php
3. Centralized API Responses & Full Multi-Language Translation (Default en / ar)
Centralized JSON Responses
All endpoints MUST return JSON through App\Support\ApiResponse (ApiResponse.php) and base Controller helpers:
jsonSuccess(mixed $data = null, ?string $message = null, int $status = 200, array $extra = [], bool $includeData = true)jsonCreated(mixed $data = null, ?string $message = null, array $extra = [])jsonOk(array $payload = [], int $status = 200)jsonError(string $message, int $status = 422, mixed $data = null, array $extra = [])jsonUnauthorized(...)/jsonForbidden(...)/jsonNotFound(...)- 0 raw
response()->json()calls inapp/Http/Controllers/**andapp/Services/**.
Full Multi-Language Policy (Default en / ar)
- Every project MUST ship with
en(LTR fallback) andar(RTL) fully translated inlang/en/messages.php,lang/ar/messages.php, andlang/ar/validation.php. - NEVER hardcode user-facing English or Arabic strings in Controllers, Services, Repositories, FormRequests (
messages()/attributes()), API Resources, Backed Enumlabel()methods, Notifications, Mailables, or Exceptions — always use__('messages.<key>', [...]). - Maintain 100% key & placeholder parity (
:name,:count,:seconds) acrossenandar(and any additional locales), verified withaudit-translations.cjs.
4. Backed Enums, FormRequests & API Resources
Backed Enums (app/Enums/)
- Use PHP 8.1+ Backed Enums (
enum Status: string,enum PriceTier: int) instead of magic strings. - Provide localized
label(): string(__('messages.*')),color(): string,icon(): string,options(): array, and safefromCode(?string $code): ?self(strtoupper(trim(...))+self::tryFrom(...)). - For live API-updated values (e.g.,
Currency::exchangeRate()), delegate to a request-scoped service (app(ExchangeRateService::class)->rateFor($this->value)) while keeping a terminal static fallback (defaultRate(): float) to prevent circular recursion. - Cast enum columns in Eloquent
casts()and validate inputs withRule::enum(MyEnum::class).
FormRequests (app/Http/Requests/**)
- Never call
$request->validate(...)inline in controllers. - Normalize inputs in
prepareForValidation()(trim strings, lowercase emails, uppercase codes, strip non-digits from OTPs). - Use array syntax for rules (
['required', 'string', 'min:8', 'confirmed', 'different:current_password']). - For bearer-token routes, resolve the user in
authorize()and exposeauthenticatedUser(): User(and optionaltoDto()).
API Resources (app/Http/Resources/*Resource.php)
- Never return raw Eloquent models directly.
- Cast scalars explicitly (
(int),(float),(bool),?string) and format dates with->toIso8601String(). - Always use
$this->whenLoaded('relation', ...)and$this->whenCounted('items')to prevent lazy-loading N+1 queries. - Guard private fields (payment handles, tokens, credentials) with
$this->when($isOwner, ...)or$this->mergeWhen(...).
5. Events, Reusable Services, Scoped Caching & N+1 Prevention
Events & Real-Time Broadcasting (app/Events/)
- Use
ShouldBroadcastNowfor latency-sensitive UI updates (chat, notifications, presence) orShouldBroadcastfor queued fan-out. - Define explicit
broadcastAs(): stringand minimalbroadcastWith(): arraypayloads onPrivateChannel('user.' . $recipientId)authorized inroutes/channels.php. - Wrap non-critical broadcasts in
try { event(...); } catch (Throwable $e) { Log::warning(...); }so socket outages never break HTTP writes. - Keep
Model::saved/Model::createdhooks non-blocking: check$model->wasRecentlyCreated || $model->wasChanged([...])and dispatch queued jobs guarded byCache::add($lockKey, true, $ttl).
Reusable Services & N+1 Prevention (app/Services/)
- Enforce
Model::preventLazyLoading(! app()->isProduction())inAppServiceProvider::boot(). - Eager-load relations with explicit columns (
->with(['owner:id,name'])) and counts (->withCount('items as items_count')). - Batch cache reads with
Cache::many($keys)and bulk DB lookups withwhereIn(...)->get()->keyBy('id'). - Chunk bulk writes via
upsert()orarray_chunk($rows, 100).
Request-Scoped Caching & Persistent Snapshots
- Bind read-heavy config/rate services with
$this->app->scoped(MyService::class). - Memoize config & snapshots in instance properties per request, and provide
flushMemoryCache(bool $syncContainer = true)on writes to keep container instances in sync. - Persist critical external API snapshots to both
Cacheand DB (app_configs) so live data survivescache:clear, with a cooldown-guarded lazy fetch on first miss outside unit tests. - Blueprint: ScopedSnapshotService.php
6. Auth Security, Middleware Stack & Encrypted Browser Responses
Global Middleware Order (bootstrap/app.php)
Register middlewares in this exact order:
->withMiddleware(function (Middleware $middleware): void {
$middleware->trustProxies(at: '*');
$middleware->append(SetAppLocale::class);
$middleware->append(SecurityHeaders::class);
$middleware->append(EncryptBrowserResponses::class);
})
SetAppLocale: Resolve locale deterministically (X-App-Localeheader →?lang=query →Accept-Language→'en'), strictly whitelisting supported locales beforeapp()->setLocale($locale).SecurityHeaders: SetX-Frame-Options: SAMEORIGIN,X-Content-Type-Options: nosniff,Referrer-Policy: strict-origin-when-cross-origin,Permissions-Policy: camera=(), microphone=(), geolocation=(), and emitStrict-Transport-Security: max-age=31536000; includeSubDomainsONLY when$request->isSecure().EncryptBrowserResponses+BrowserResponseCrypto(AES-256-GCM):issueBrowserBundle()generates a 32-byte ephemeral AES key + TTL-boundCrypt::encryptStringX-Transport-Token.- On opt-in requests (
X-Encrypted-Response: 1+ validX-Transport-Token), encrypt JSON bodies withaes-256-gcm(base64(12B IV || ciphertext || 16B tag)), preserve headers/cookies, setContent-Type: application/octet-stream,X-Response-Encrypted: 1,Cache-Control: no-store, no-cache, must-revalidate, private, andVary: X-Encrypted-Response. - Skip
admin*,livewire*, Telescope path,BinaryFileResponse,StreamedResponse,204, empty, and non-JSON responses. - Application-layer payload encryption is defense-in-depth and never replaces HTTPS/TLS, authentication, or authorization.
- Blueprint: MiddlewareSecurityLocaleCrypto.php
Auth Security Hardening (config/auth_security.php, AuthSecurityService)
- Track login/OTP failures across all linked identifiers simultaneously (
user_id, normalizedphone, lowercasedemail). - Escalate progressively: CAPTCHA challenge (
turnstile/hcaptcha/recaptcha/log) →429lockout withRetry-After. - Layer
RateLimiterrules inAppServiceProvider: per-IP + per-normalized-phone limits (10/min/IP+5/min&20/hrper phone). - Authenticated password changes (
PATCH /api/v1/auth/password) verifyHash::check($current, $user->password)and throttle withauth-login.
New Project Security Checklist (Apply on Day 1)
When bootstrapping any new Laravel project, enforce these baseline security controls immediately:
- Secrets & Environment: Never commit
.envor private keys; keep.env.exampleplaceholder-only; enforceAPP_DEBUG=falsein production; gate debug tools (Telescope,Horizon) behind non-guessable paths and admin auth. - Mass Assignment & SQLi: Define explicit
$fillableon every model (never$guarded = []on user-editable models); pass only$request->validated()or typed DTOs; never interpolate user input intoDB::raw()/whereRaw()/orderByRaw()— bind parameters and whitelist sort columns. - IDOR & Authorization: Enforce Policies (
Gate::authorize(...)) or explicit ownership checks ($model->isOwnedBy($user)) on every read/write of user-owned records; consider ULIDs/UUIDs for public resource IDs. - CORS & Cookies: Never combine
allowed_origins => ['*']withsupports_credentials => trueinconfig/cors.php; whitelist exact frontend origins and setSESSION_SECURE_COOKIE=true,http_only=true,same_site=lax,SESSION_ENCRYPT=true. - File Uploads & SSRF: Validate uploads by MIME + extension + max size, store with random
Str::uuid()names on private/non-executable disks; restrict outbound HTTP calls tohttps://allowlisted hosts (blocking loopback/private metadata IPs like127.0.0.1and169.254.169.254). - Dependency & Token Hygiene: Run
composer audit(andnpm auditif frontend exists); revoke old tokens on password change/reset; never leak account existence on forgot-password endpoints.
7. Postman Collection (API Projects) & Local Composer Packages
Postman Collection v2.1.0 (postman/<project-slug>.postman_collection.json)
Whenever a project exposes endpoints in routes/api.php:
- Create and maintain a valid Postman v2.1.0 collection grouped by domain/controller.
- Define collection variables:
base_url,api_prefix,token,locale(en/ar). - Set collection-level
bearerauth ({{token}}), override withnoauthon public routes, and includeAccept: application/json+X-App-Locale: {{locale}}. - Match request JSON bodies and query/path params to each
FormRequest, attach a post-responsetestscript on Login/Register to auto-savepm.collectionVariables.set('token', ...), and update the collection whenever API routes or contracts change. - Blueprint: postman_collection.template.json
First-Party Local Composer Packages (packages/<vendor>/<name>)
- Extract owned or unmaintained dependencies into
packages/<vendor>/<name>/with PSR-4 autoloading,extra.laravel.providers, and a rootcomposer.jsonpathrepository ("symlink": true), removing all legacy vendor references.
8. Blueprints, Automated Audits & Mandatory Verification
Copy-Paste Blueprints
- ModuleServiceProviderTemplate.php — Self-Contained Module
ServiceProvider(Bindings, Routes, Migrations & Translations) - StrategyAndDecoratorTemplate.php — Value Object, Strategy + Resolver, Decorator & Container Tagging
- RepositoryTemplate.php — Contract, Repository, Binding & Thin Controller
- ApiResponse.php — Centralized JSON Response Builder
- ScopedSnapshotService.php — Scoped Memoized Service with Cache + DB Fallback
- MiddlewareSecurityLocaleCrypto.php —
SetAppLocale,SecurityHeaders,BrowserResponseCrypto&EncryptBrowserResponses - postman_collection.template.json — Postman v2.1.0 Collection Blueprint
Verification Checklist Before Finishing Any Task
- Run all automated audits:
node ./skills/laravel-clean-pattern/scripts/audit-controllers.cjs app/Http/Controllers node ./skills/laravel-clean-pattern/scripts/audit-responses.cjs . node ./skills/laravel-clean-pattern/scripts/audit-translations.cjs . en,ar - Lint modified PHP files (
php -l <file>). - Run PHPUnit feature & unit suites (
php artisan test), includingDB::enableQueryLog()O(1) query assertions for N+1-sensitive endpoints. - If
routes/api.phpwas created or modified, updatepostman/<project-slug>.postman_collection.jsonand validate JSON syntax.
