Back to All Nuggets
Laravel php ⏱️ 6 min read
Production Implementation
Ask endoAI
<?php

declare(strict_types=1);

namespace App\Models;

use App\Enums\ConsultationStatus;
use App\Models\Scopes\TenantScope;
use App\ValueObjects\VitalSigns;
use Illuminate\Database\Eloquent\Attributes\ScopedBy;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * Enterprise Multi-Tenant Consultation Model
 * 
 * Demonstrates modern Laravel 11/13 patterns:
 * - Attribute-driven ScopedBy for automated multi-tenancy
 * - Modern casts() method returning Enums and Value Objects
 * - Strict relationship integrity and eager-loading guards
 */
#[ScopedBy([TenantScope::class])]
class Consultation extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'tenant_id',
        'facility_id',
        'patient_id',
        'doctor_id',
        'status',
        'vital_signs',
        'clinical_notes',
        'attended_at',
    ];

    /**
     * Modern method-based casts definition (Laravel 11 / 13)
     */
    protected function casts(): array
    {
        return [
            'status' => ConsultationStatus::class,
            'vital_signs' => VitalSigns::class,
            'clinical_notes' => 'encrypted',
            'attended_at' => 'immutable_datetime',
        ];
    }

    public function patient(): BelongsTo
    {
        return $this->belongsTo(Patient::class)->withDefault([
            'full_name' => 'Anonymous Patient',
            'mrn' => 'PENDING',
        ]);
    }

    public function doctor(): BelongsTo
    {
        return $this->belongsTo(Doctor::class);
    }

    /**
     * High-performance compound index scope
     * Aligned with compound index: (tenant_id, status, attended_at)
     */
    public function scopePendingReview(Builder $query, int $facilityId): Builder
    {
        return $query->where('facility_id', $facilityId)
                     ->where('status', ConsultationStatus::Pending)
                     ->orderBy('attended_at', 'asc');
    }
}

Bridging the Chasm Between Tutorial Theory and Enterprise Reality

Most online software engineering tutorials teach happy-path web development: a single controller querying Post::all(), migrations without foreign key constraints, unindexed foreign keys, and casual .env calls scattered throughout business logic. While sufficient for hobby projects, this approach inevitably collapses under production enterprise demands.

In high-throughput environments—such as clinical hospital management systems, financial settlement ledgers, and multi-tenant SaaS platforms—the database layer is where scalability either succeeds or silently degrades. Over the past few weeks in our Enterprise Laravel Masterclass at Endo Systems, our developers have tackled 20 intensive laboratory benchmarks. Each lab presents a rigorous architectural challenge verified by automated real-time benchmarks.

Below, we unpack the five core architectural disciplines proven hands-on in our labs, accompanied by production blueprints and performance strategies.


Pillar 1: Dual-Engine Architecture (SQLite Sandbox + MySQL Concurrency)

In Laravel 13, SQLite serves as the default zero-configuration database engine for local prototyping and in-memory test suites. Running test suites against SQLite in-memory (:memory:) delivers up to 15x faster execution compared to spun-up Dockerized MySQL instances, enabling instant feedback loops during Test-Driven Development (TDD).

  • Synchronized Configuration Contracts: Never let .env.example fall behind. Every required secret, database fallback, and Redis connection key must be documented with sane sandbox defaults.
  • The Serialization Trap (php artisan config:cache): Once configuration is cached in staging or production, calls to env() outside of config/*.php files resolve to null. All application code must strictly consume values via config('services.name').
  • Artisan Introspection: Senior engineers diagnose table states from the terminal. Commands like php artisan db:show and php artisan db:table consultations instantly expose active PDO drivers, open connections, table byte size, unindexed foreign keys, and column nullability without opening an external GUI.

Pillar 2: Defensive Schema Design & Composite Indexing Strategies

Database migrations are the immutable foundation of your schema. A single careless migration can introduce locking latency or catastrophic data loss.

The Danger of Casual Cascading Deletes

Using $table->foreignId('tenant_id')->constrained()->cascadeOnDelete(); is one of the most hazardous anti-patterns in multi-tenant or medical software. If a staff member or automated cleaner deletes a parent organization, cascading deletes will silently obliterate thousands of clinical consultations, lab results, and financial invoices without triggering audit logs.

In our labs, developers implement defensive deletion strategies:

  • restrictOnDelete(): Enforced on financial, medical, and legal records. The database engine rejects deletion of any parent record while child records exist.
  • nullOnDelete(): Used for optional foreign relationships (e.g. assigned_nurse_id), preserving the underlying consultation even if the assigned staff profile is archived.
  • Two-Phase Soft Deletes: State-based archiving with explicit timestamp auditing before any physical purge is considered.

The Leftmost Prefix Rule in Composite B-Tree Indexing

When millions of rows populate a table, single-column indexes become insufficient. When creating composite indexes—such as $table->index(['tenant_id', 'status', 'created_at']);—the database B-tree query planner relies strictly on the leftmost prefix rule:

  • Queries filtering by tenant_id and status will perform an ultrafast index seek.
  • Queries filtering by tenant_id alone will utilize the index.
  • Queries filtering only by status or created_at cannot use the index and will revert to a full table scan.
  • Rule of thumb: Place highest-cardinality equality filter columns first, followed by range or sorting columns.

Pillar 3: Modern Eloquent & Eliminating N+1 Query Regressions

Laravel 11 and 13 introduce cleaner, more expressive paradigms that replace legacy patterns while enforcing architectural boundaries.

Method-Based casts() vs Property Arrays

Rather than declaring an array property protected $casts = [...], modern models utilize the protected function casts(): array method. This unlocks dynamic casts, PHP 8.2+ backed enums, value objects, and native database encryption with zero serialization overhead:

Code
protected function casts(): array
{
    return [
        'status' => ConsultationStatus::class,
        'vital_signs' => VitalSigns::class,
        'clinical_notes' => 'encrypted',
        'attended_at' => 'immutable_datetime',
    ];
}

Strict Mode in Development

To prevent N+1 query regressions from escaping into production, we teach developers to enable Eloquent strict mode inside their AppServiceProvider::boot():

Code
public function boot(): void
{
    Model::shouldBeStrict(! $this->app->isProduction());
}

This single line simultaneously enforces:

  1. preventLazyLoading(): Throws an exception the instant an un-eager-loaded relation is accessed inside a loop.
  2. preventSilentlyDiscardingAttributes(): Alerts developers when attributes are missing from $fillable.
  3. preventAccessingMissingAttributes(): Catches typos when accessing non-existent database columns on a model.

Pillar 4: Multi-Tenant Schema Isolation via Global Scopes

Managing separate physical databases for thousands of tenants introduces substantial operational overhead, connection exhaustion, and migration latency. Single-database multi-tenancy remains the gold standard for high-density SaaS—provided data isolation is guaranteed at the ORM layer.

In our masterclass, we teach developers to implement attribute-driven tenant scoping using the PHP 8 attribute #[ScopedBy([TenantScope::class])]. The scope automatically binds the authenticated tenant's identity to every SELECT, INSERT, UPDATE, and DELETE query. Furthermore, by implementing macro('withoutTenant'), background aggregation jobs can explicitly bypass the scope with complete audit logging.


Pillar 5: High-Throughput Seeding & Memory Streaming

Enterprise systems frequently ingest massive external data dumps—such as national medication registries, ICD-10 biomedical diagnostic codes, or historical CSV logs. Attempting to seed 100,000 records using standard factory loops rapidly exhausts memory limits.

Our labs teach two essential data pipeline patterns:

  • Model Recycling: Using $factory->recycle($existingUser)->create() prevents nested factories from generating redundant parent entities, keeping test databases lean and relational trees intact.
  • Generator-Based Streaming: Using PHP Generators (yield) and Laravel's LazyCollection / chunkById() allows ingestion of multi-gigabyte files while maintaining a constant memory footprint below 32MB.

Behind the Scenes: Engineering the Automated Lab Evaluation Engine

To ensure developers truly internalize these concepts, we built an automated, real-time evaluation workbench directly inside the Endo Academy portal. When a developer submits their implementation and terminal output:

  • Multi-Benchmark Parsing: The evaluator runs automated verification suites testing CLI execution, regex pattern matching, schema syntax, and model constraints.
  • 70% Mastery Benchmark: Only submissions achieving 70% or higher are marked complete, ensuring solid comprehension before progressing.
  • Offline Resiliency & Auto-Save: Edits are continuously mirrored to local browser storage, debounced to cloud auto-save, and protected by automatic HTTP 419 CSRF token recovery.

Level Up Your Engineering Career

Unlock All 20 Hands-On Labs in the Enterprise Laravel Masterclass

Reading articles gives you knowledge—but writing production code, debugging real database constraints, and passing automated benchmarks transforms you into a high-earning senior engineer.

Everything You Get With Full Subscription Access:
  • ✓ Full Interactive Access to All 20 Labs: Terminal execution guides, starter blueprints, and automated verification suites.
  • ✓ Automated Grading Workbench: Real-time feedback and diagnostic test results on your migrations, queries, and models.
  • ✓ Live Google Meet Architecture Reviews: Direct code feedback and Q&A sessions with seasoned instructors.
  • ✓ Official Verified Certificate: Digital credential with a public authenticity verification URL to showcase on LinkedIn and CVs.
  • ✓ Curated Senior Code Nuggets Library: Ongoing access to production blueprints across Laravel, AI, and Systems.
Monthly Membership: KES 500 / month (Cancel anytime)

Already have an active subscription? Open your Developer Lab Portal

Accelerate Your Engineering Career

Get monthly masterclasses, exclusive code snippets, and direct architectural reviews.

Become a Supporter • KES 500 / Month