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 Data Laravel Package

spatie/laravel-data

Define rich, typed data objects once and use them for requests, validation, API resources/transformers, and TypeScript definitions. Create from arrays/requests/models, apply rules automatically, and transform only what’s needed with lazy properties.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Strong alignment with Laravel ecosystem: The package is purpose-built for Laravel, leveraging its core features (Eloquent, Form Requests, API Resources) while introducing a unified data layer. This reduces redundancy in validation, serialization, and type safety across the stack.
  • Domain-Driven Design (DDD) compatibility: Encourages modeling data as immutable objects, aligning with DDD principles. Ideal for applications requiring strict data contracts (e.g., microservices, APIs, or complex business logic).
  • Separation of concerns: Decouples data validation, transformation, and serialization logic from controllers/models, improving maintainability and testability.
  • TypeScript integration: Generates frontend types automatically, reducing manual effort in API contracts and improving developer experience.

Integration Feasibility

  • Low friction for Laravel apps: Minimal setup (composer install + config) and seamless integration with existing Laravel components (Form Requests, Eloquent, API Resources).
  • Backward compatibility: Designed to coexist with existing patterns (e.g., Form Requests, API Resources) without forcing a rewrite. Can be adopted incrementally.
  • Customization hooks: Supports custom casts, transformers, and validation logic, allowing adaptation to niche use cases (e.g., legacy systems or non-standard data formats).
  • Performance considerations: Reflection-based analysis adds overhead during development, but caching (php artisan data:cache-structures) mitigates this in production.

Technical Risk

  • Reflection dependency: Heavy use of reflection may impact performance during development or in environments where caching isn’t feasible (e.g., serverless functions). Mitigation: Pre-cache structures in CI/CD pipelines.
  • Learning curve: Requires adopting a new paradigm (data objects over DTOs/Requests). Teams unfamiliar with immutable objects or PHP’s type system may face ramp-up time.
  • Tooling gaps: Limited IDE support for data objects (e.g., autocompletion, refactoring) compared to traditional classes. Mitigation: Use PHPStan or IDE plugins to bridge gaps.
  • Versioning: As a v4 package, long-term stability is unproven. Monitor Spatie’s release cycle and Laravel compatibility (e.g., PHP 8.2+ features).

Key Questions

  1. Adoption scope:
    • Will this replace all Form Requests/API Resources, or only new features? Partial adoption may lead to inconsistency.
    • How will existing validation logic (e.g., custom rules) migrate to data objects?
  2. Performance:
    • What’s the acceptable trade-off between development-time reflection and production caching?
    • Will the app’s data object count (e.g., 50 vs. 500+) impact caching effectiveness?
  3. Team alignment:
    • Does the team have experience with immutable objects or DDD? If not, budget for training.
    • How will frontend teams leverage TypeScript generation (e.g., API versioning, breaking changes)?
  4. Long-term maintenance:
    • Who will own data object definitions (e.g., backend vs. shared codebase)?
    • How will data objects evolve alongside API contracts (e.g., deprecation, versioning)?

Integration Approach

Stack Fit

  • Laravel-native: Optimized for Laravel’s ecosystem (Eloquent, API Resources, Form Requests). Avoids reinventing wheels (e.g., no need for separate DTO libraries like symfony/serializer).
  • PHP 8.2+ features: Leverages modern PHP (construct property promotion, attributes) for cleaner syntax. Requires PHP 8.1+.
  • Frontend synergy: TypeScript generation reduces context-switching for full-stack teams. Works well with frameworks like Vue/React/Angular.
  • Microservices/APIs: Ideal for services where data contracts are critical (e.g., GraphQL, REST APIs with strict schemas).

Migration Path

  1. Pilot phase:
    • Start with non-critical endpoints (e.g., internal APIs, admin panels) to test the paradigm shift.
    • Replace one Form Request/API Resource pair with a data object at a time.
  2. Incremental adoption:
    • Validation: Replace FormRequest validation with data object type hints + custom casts.
    • Serialization: Replace ApiResource with Data objects for API responses.
    • Frontend: Gradually migrate to TypeScript types generated from data objects.
  3. Tooling integration:
    • Configure php artisan data:cache-structures in CI/CD pipelines (e.g., post-deploy).
    • Set up PHPStan to enforce data object usage where applicable.
  4. Legacy support:
    • Use WithData trait to retroactively add data object support to existing models/requests.
    • Implement custom casts/transformers to bridge legacy data formats.

Compatibility

  • Laravel versions: Officially supports Laravel 10+ (check docs for exact versions).
  • PHP versions: Requires PHP 8.1+ (for constructor property promotion). Test compatibility with PHP 8.3 if using nightly features.
  • Dependencies:
    • Conflicts: None major (uses Laravel’s core components).
    • Dependents: None (standalone package), but ensure no overlapping functionality with other DTO packages (e.g., spatie/array-to-object).
  • Database: No direct DB integration, but works with Eloquent models via WithData trait.

Sequencing

  1. Phase 1: Core Data Objects
    • Define data objects for core domain models (e.g., UserData, OrderData).
    • Replace Form Request validation with data object type hints.
  2. Phase 2: API Layer
    • Replace ApiResource with data objects for API responses.
    • Generate TypeScript types and integrate with frontend.
  3. Phase 3: Full Stack
    • Extend to internal services (e.g., queues, events) using data objects.
    • Implement custom casts for complex types (e.g., nested objects, enums).
  4. Phase 4: Optimization
    • Cache data structures in production.
    • Monitor performance and adjust caching strategy (e.g., Redis vs. file cache).

Operational Impact

Maintenance

  • Reduced boilerplate: Eliminates duplicate validation/serialization logic (e.g., no more syncing between Form Requests and API Resources).
  • Centralized definitions: Data contracts live in one place (data objects), reducing drift over time.
  • Validation logic: Moves from scattered rules() methods to type hints + custom casts, making validation rules easier to maintain.
  • Breaking changes:
    • Adding/removing properties in data objects may break frontend/API consumers. Use semantic versioning for data object changes.
    • Custom casts/transformers require updates if their logic changes.

Support

  • Debugging:
    • Data objects provide clear error messages for type mismatches (e.g., invalid input during creation).
    • Use dd($dataObject) to inspect structure and validation errors.
  • Tooling:
    • Leverage PHPStan to catch type issues early.
    • Generate TypeScript types to catch frontend/backend mismatches during development.
  • Documentation:
    • Data objects serve as self-documenting contracts. Supplement with comments for complex logic (e.g., custom casts).
    • Maintain a DATA_OBJECTS.md file listing all data objects and their purposes.

Scaling

  • Performance:
    • Development: Reflection overhead may slow down IDE tools (e.g., autocompletion). Mitigate with caching.
    • Production: Caching (data:cache-structures) ensures minimal runtime overhead. Benchmark with 10K+ data objects if scaling horizontally.
  • Team scaling:
    • Data objects enable parallel development (e.g., frontend and backend can work on types independently).
    • Clear contracts reduce miscommunication between teams.
  • Infrastructure:
    • No additional infrastructure needed beyond Laravel’s cache (e.g., Redis for caching).
    • Consider caching strategies for large-scale apps (e.g., distributed cache for microservices).

Failure Modes

  • Data corruption:
    • Immutable data objects prevent accidental mutations, but ensure custom casts/transformers handle edge cases (e.g., invalid input).
    • Use try-catch blocks around data object creation to handle Uncastable exceptions gracefully.
  • Caching issues:
    • Stale cached structures may cause runtime errors. Invalidate cache after deploying data object changes:
      php artisan data:cache-structures --force
      
  • Type safety gaps:
    • PHP’s dynamic nature may bypass type hints in some cases (e.g., dynamic properties). Use PHPStan to enforce strictness.
  • Frontend misalignment:
    • TypeScript types may lag behind data object changes. Implement a CI check to validate type generation.

Ramp-Up

  • Onboarding:
    • For backend devs: Focus on replacing Form Requests/API Resources with data objects. Provide a cheat sheet for common patterns (e.g., nested objects, validation).
    • For frontend devs: Highlight TypeScript generation and how to use it with API clients (e.g., OpenAPI/Swagger).
  • Training:
    • Workshops: Hands-on session to build a data object from scratch (e.g., migrate a StoreRequest to StoreData).
    • Documentation: Create
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport