Middleware
The CPR backend uses custom middleware for branch isolation, rate limiting, and request processing.
Custom Middleware
EnsureBranchContext
The most important custom middleware — enforces multi-branch data isolation on branch-scoped routes.
Location: app/Http/Middleware/EnsureBranchContext.php
What it does:
- Resolves the branch ID from (in priority order):
X-Branch-IdHTTP headerbranch_idquery parameter- User's
default_branch_id
- Validates the branch exists
- Validates the user has access to that branch (via
branch_userspivot) - Sets
current_branch_idon the request for downstream use
Error responses:
| Scenario | Status | Message |
|---|---|---|
| No branch context provided | 400 | Branch context required |
| User doesn't have access to branch | 403 | Access denied to this branch |
Applied to: All branch-scoped routes (patients, visits, exams, queue, billing, dashboard).
Usage in routes:
php
Route::middleware(['auth:sanctum', 'branch.context'])->group(function () {
Route::apiResource('patients', PatientController::class);
Route::apiResource('patient-visits', PatientVisitController::class);
// ... all branch-scoped routes
});Client usage:
http
GET /api/v1/patients
Authorization: Bearer {token}
X-Branch-Id: 1HandleAppearance
Reads the appearance cookie (theme preference) and shares it with views.
- Default:
'system' - Shares via
View::share('appearance', $value)
HandleInertiaRequests
Inertia.js middleware for the web frontend:
- Sets root view to
'app' - Shares common props: app name, auth user, sidebar state
- Reads sidebar state from cookie
Framework Middleware
The application also uses these Laravel/Sanctum middleware:
| Middleware | Alias | Purpose |
|---|---|---|
auth:sanctum | - | Authenticates Bearer token |
throttle:api | - | Rate limit: 1000 req/min per user |
throttle:authentication | - | Rate limit: 5 req/min per IP |
throttle:public | - | Rate limit: 5 req/min per IP |
permission:{name} | - | Spatie permission check (e.g., permission:admin.access) |
Middleware Stack per Route Type
Public Routes
throttle:publicAuthentication Routes
throttle:authenticationStandard API Routes
throttle:api → auth:sanctumBranch-Scoped Routes
throttle:api → auth:sanctum → branch.contextAdmin Routes
throttle:api → auth:sanctum → permission:admin.accessRate Limiting Configuration
Rate limits are defined in AppServiceProvider::configureRateLimiting():
php
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(1000)
->by($request->user()?->id ?: $request->ip());
});
RateLimiter::for('authentication', function (Request $request) {
return Limit::perMinute(5)->by($request->ip());
});
RateLimiter::for('public', function (Request $request) {
return Limit::perMinute(5)->by($request->ip());
});