Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Computed Attributes Laravel Package

korridor/laravel-computed-attributes

Adds “computed attributes” to Laravel models, letting you define dynamic/derived properties that behave like normal attributes (including access/casting/serialization) without storing them in the database. Useful for clean model APIs and reusable calculations.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Elquent-Centric Design: Perfectly aligns with Laravel’s Eloquent ORM, leveraging accessors/mutators for computed logic while persisting results to the database. Avoids reinventing wheel for common patterns (e.g., caching, dirty checks).
  • Materialized Views Alternative: Acts as a lightweight, application-layer alternative to database-level computed columns (e.g., MySQL’s GENERATED ALWAYS AS), with the flexibility to handle complex PHP logic (e.g., API calls, conditional logic).
  • Event-Driven Integration: Seamlessly integrates with Laravel’s model events (updating, saved, etc.), enabling fine-grained control over recomputation triggers.
  • Hybrid Workflows: Supports both real-time (cached) and on-demand (uncached) computations, with explicit control via cache flag or recompute() calls.

Integration Feasibility

  • Minimal Boilerplate: Requires only:
    1. Composer install.
    2. Configuration publish (artisan vendor:publish).
    3. Model trait usage (use HasComputedAttributes).
    4. Attribute definition in $computedAttributes.
  • Backward Compatibility: Supports Laravel 10–13 (with explicit versioning) and PHP 8.1–8.3, reducing migration risk.
  • Database Agnostic: Works with any Laravel-supported database (MySQL, PostgreSQL, SQLite), though performance may vary for non-MySQL (e.g., PostgreSQL’s JSONB support for StoresComputedAttributesInJson).
  • Testing Support: Includes unit tests and Artisan commands (computed-attributes:validate) for validation, easing adoption in CI/CD pipelines.

Technical Risk

  • Schema Changes: Adds new columns to tables (one per computed attribute), requiring migrations. Risk mitigated by:
    • Default nullable columns (backward-compatible).
    • Artisan command to validate existing data (artisan computed-attributes:validate).
  • Performance Overhead:
    • Write Path: Computations run on save(), adding latency. Mitigate with:
      • skip_on_create flag for non-critical attributes.
      • Queue jobs for expensive computations (e.g., API calls).
    • Read Path: Cached values reduce queries, but stale data risk exists. Mitigate with:
      • Explicit invalidateComputedAttribute() calls.
      • Short TTLs for volatile data.
  • Complexity Sprawl:
    • Debugging: Computed attributes can obscure data lineage. Mitigate with:
      • Logging hooks (ComputedAttributes::computing()).
      • isComputedAttributeCached() checks.
    • Infinite Loops: Circular dependencies between computed attributes. Mitigate with:
      • cache: false for dependent attributes.
      • Static analysis (PHPStan) to detect patterns.
  • Long-Term Maintenance:
    • Vendor Lock-in: Minimal (MIT license, open-source). Risk of package abandonment is low given active releases (2026-05-11) and CI/CD integration.
    • Laravel Versioning: Tight coupling to Laravel versions (e.g., v3.x requires Laravel 10+). Risk mitigated by:
      • Clear versioning strategy (e.g., v2.x for older Laravel).
      • Compatibility matrix in README.

Key Questions

  1. Data Consistency:
    • How will we handle cases where computed attributes depend on external systems (e.g., APIs, microservices)? Will we use cache: false or queue jobs?
    • Example: user_reputation_score fetched from a third-party service.
  2. Schema Management:
    • Should computed attributes be optional columns (nullable) or required? How will we handle backfilling during migration?
  3. Performance Tradeoffs:
    • For high-write workloads (e.g., 10K+ updates/hour), will the overhead of recomputing on save() be acceptable? If not, should we explore:
      • Database triggers (e.g., MySQL BEFORE UPDATE).
      • Event-driven architectures (e.g., Laravel Horizon queues).
  4. Testing Strategy:
    • How will we test computed attributes in CI/CD? Will we use the computed-attributes:validate command or custom assertions?
    • Example: Verify order_total matches subtotal + tax after updates.
  5. Monitoring:
    • Should we track computation latency or cache hit ratios in production? Tools like Laravel Telescope or Prometheus could help.
  6. Fallbacks:
    • What’s the plan if the computation fails (e.g., API timeout)? Will we:
      • Store the error in the computed column?
      • Use a null value with a fallback logic?
  7. Team Adoption:
    • How will we document computed attributes for future developers? Suggestions:
      • Add a @computed PHPDoc tag to models.
      • Include examples in the README for common use cases (e.g., pricing, analytics).
  8. Alternatives:
    • For read-heavy workloads, would database-level computed columns (e.g., PostgreSQL GENERATED) be more performant?
    • For event-sourced systems, would a CQRS approach (e.g., Laravel Scout) be better?

Integration Approach

Stack Fit

  • Laravel Ecosystem: Native support for Laravel 10–13, PHP 8.1–8.3, and Eloquent. Integrates with:
    • Artisan: Commands for validation/generation (computed-attributes:validate).
    • Events: Hooks into updating, saved, etc.
    • Testing: Mockable computations for unit/feature tests.
    • CI/CD: GitHub Actions with PHPStan for static analysis.
  • Database Compatibility:
    • MySQL/PostgreSQL: Full support (with JSONB for StoresComputedAttributesInJson).
    • SQLite: Limited (no computed columns; relies on PHP logic).
  • Tooling:
    • IDE Support: PHPDoc types and IDE hints for computed attributes.
    • Debugging: Logging hooks and isDirty() checks for debugging.

Migration Path

  1. Assessment Phase:
    • Audit existing models to identify candidates for computed attributes (e.g., derived fields, aggregations).
    • Example: Replace manual order_total = subtotal + tax logic in controllers with a computed attribute.
  2. Pilot Phase:
    • Start with non-critical models (e.g., analytics dashboards, reporting tables).
    • Use cache: false initially to validate logic before enabling persistence.
  3. Incremental Rollout:
    • Step 1: Add computed attributes to models without migrations (use nullable columns).
    • Step 2: Backfill existing data using artisan computed-attributes:validate or a custom seeder.
    • Step 3: Enable caching and optimize TTLs based on access patterns.
  4. Deprecation:
    • Phase out manual computed logic (e.g., controller calculations) in favor of the package.
    • Example: Remove OrderController@calculateTotal() if order_total is now a computed attribute.

Compatibility

  • Existing Code:
    • Accessors/Mutators: Computed attributes override existing accessors. Use recomputeComputedAttribute() to force updates.
    • Fillable/Mass Assignment: Computed attributes can be included in $fillable but require explicit handling to avoid infinite loops.
    • Serializers (e.g., Laravel API Resources): Ensure computed attributes are included in $appends or explicitly added.
  • Third-Party Packages:
    • Laravel Scout: Computed attributes can be indexed if marked as appends.
    • Laravel Nova: Requires custom field definitions to display computed attributes.
    • Eloquent Relationships: Computed attributes work across relationships (e.g., user.order.total).

Sequencing

  1. Prerequisites:
    • Laravel 10+ (recommended: 13 for full feature support).
    • PHP 8.1+ (8.3 for type safety).
    • Composer and Node.js (for CI/CD tools like PHPStan).
  2. Installation Order:
    composer require korridor/laravel-computed-attributes
    php artisan vendor:publish --provider="Korridor\ComputedAttributes\ComputedAttributesServiceProvider" --tag="config"
    
  3. Configuration:
    • Adjust config/computed-attributes.php (e.g., default TTL, storage engine).
    • Example: Set default_cache_ttl to 3600 for frequently accessed attributes.
  4. Model Integration:
    • Add use HasComputedAttributes to target models.
    • Define $computedAttributes array (start with 1–2 attributes per model).
  5. Testing:
    • Write unit tests for computations (mock dependencies).
    • Run artisan computed-attributes:validate to check existing data.
  6. Deployment:
    • Roll out in stages (e.g., start with read-only attributes).
    • Monitor performance (
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle