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

Create rich, typed data objects for Laravel that replace form requests and API transformers. Automatically map from requests, validate with inferred rules, transform to resources (with lazy/partial fields), and generate TypeScript definitions from the same source.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Strong alignment with Laravel’s ecosystem: The package leverages Laravel’s existing patterns (e.g., API resources, form requests, Eloquent models) while introducing a unified data abstraction layer. This reduces redundancy (e.g., no need to duplicate validation rules, API responses, or TypeScript definitions).
  • Type safety: Enforces PHP types at compile time, reducing runtime errors and improving developer experience. The generated TypeScript types further bridge frontend/backend consistency.
  • Separation of concerns: Encourages a clean architecture by centralizing data contracts (e.g., Data objects) separate from business logic, validation, or presentation layers.
  • Lazy loading: Supports partial data fetching (e.g., Lazy properties) for performance-critical APIs, aligning with modern microservices and pagination needs.

Integration Feasibility

  • Low friction for Laravel apps: Designed for seamless integration with Laravel’s core features (e.g., form requests, API resources, Eloquent). Minimal boilerplate required for basic use cases.
  • Backward compatibility: Works alongside existing Laravel patterns (e.g., FormRequests, API Resources) without forcing a full rewrite. Can be adopted incrementally.
  • Customization hooks: Extensible via:
    • Property mappers (e.g., CamelCaseMapper, SnakeCaseMapper) for API/DB consistency.
    • Transformers/Casts for complex type conversions (e.g., dates, enums).
    • Validation rules tied to data properties.
  • Package isolation: MIT-licensed and dependency-light (no heavy frameworks), reducing risk of conflicts.

Technical Risk

  • Learning curve: Developers unfamiliar with data-driven design may need time to adopt the pattern (e.g., replacing FormRequests with Data objects). Requires team buy-in for consistency.
  • Overhead for simple apps: May introduce unnecessary complexity for projects with minimal data contracts or no frontend (e.g., CLI tools, internal scripts).
  • TypeScript generation: Requires frontend teams to adopt the generated types, which may not be feasible for legacy or non-TypeScript projects.
  • Performance implications:
    • Reflection-based property handling could add minor overhead in hot paths (though likely negligible for most use cases).
    • Lazy properties add memory management complexity for deeply nested data.
  • Migration path: Replacing existing FormRequests/API Resources with Data objects requires refactoring, though the package provides tools (e.g., WithData trait) to ease the transition.

Key Questions

  1. Adoption scope:
    • Will this replace all FormRequests/API Resources, or just new features?
    • How will existing validation logic (e.g., custom rules in FormRequests) migrate to Data objects?
  2. Frontend compatibility:
    • Does the frontend team use TypeScript? If not, how will the generated types be utilized?
    • Are there existing API contracts (e.g., OpenAPI/Swagger) that must remain unchanged?
  3. Performance:
    • Are there performance-critical endpoints where lazy loading or reflection could introduce latency?
    • How will data objects be cached (e.g., for repeated API responses)?
  4. Testing:
    • How will existing tests (e.g., for FormRequests) adapt to Data objects?
    • Does the team have experience with data-driven testing (e.g., property-based testing)?
  5. Tooling:
    • Will IDE support (e.g., autocompletion, refactoring) for Data objects be sufficient?
    • Are there plans to integrate with Laravel’s Pint, Pest, or other tooling?
  6. Long-term maintenance:
    • How will the team handle future Laravel version upgrades (e.g., PHP 9+ features)?
    • Is there a plan for backward compatibility if the package evolves?

Integration Approach

Stack Fit

  • Laravel-centric: Optimized for Laravel 10+ (PHP 8.1+), with deep integration into:
    • Validation: Replaces FormRequest validation logic with type-safe Data objects.
    • API Resources: Eliminates the need for separate Resource classes by using Data objects for serialization.
    • Eloquent: Supports storing Data objects as model properties (e.g., Song::first()->getData()).
    • Frontend: Generates TypeScript interfaces from PHP Data classes.
  • Non-Laravel compatibility: While designed for Laravel, the core Data class is framework-agnostic and could be used in:
    • Symfony (via spatie/laravel-data’s underlying logic).
    • Livewire/Inertia: For rich frontend interactions with typed data.
    • CLI tools: For typed configuration or command inputs.
  • Third-party integrations:
    • API Platform: Could replace serializers with Data objects.
    • Filament/Spatie Admin: For typed form/model interactions.
    • Laravel Nova: For custom field types backed by Data objects.

Migration Path

  1. Pilot phase (low risk):
    • Start with new features or non-critical endpoints to test the pattern.
    • Replace FormRequests with Data objects for validation (e.g., UserData::from($request->all())->validate()).
    • Use WithData trait on models/requests for quick adoption.
  2. Incremental replacement:
    • API Resources: Replace with Data objects for serialization (e.g., SongData::from($song)->toArray()).
    • Validation: Migrate custom validation rules from FormRequests to Data object methods (e.g., rules()).
    • Frontend: Gradually adopt generated TypeScript types.
  3. Full adoption:
    • Replace all FormRequest/API Resource classes with Data objects.
    • Update frontend contracts to use generated types.
    • Deprecate legacy patterns via feature flags or middleware.

Compatibility

  • Laravel versions: Tested on Laravel 10+ (PHP 8.1+). May require adjustments for older versions (e.g., PHP 8.0’s named arguments).
  • PHP extensions: Relies on standard PHP features (no custom extensions). May need json_encode/decode polyfills for edge cases.
  • Database: No direct DB coupling, but works with Eloquent models for persistence. Ensure property mappers align with DB column names.
  • Caching: Supports caching Data objects (e.g., via Laravel’s cache or Redis), but requires explicit implementation.
  • Testing: Compatible with Laravel’s testing tools (Pest, PHPUnit). Use LaravelDataServiceProvider in test cases for config access.

Sequencing

  1. Setup:
    • Install the package: composer require spatie/laravel-data.
    • Publish config (if needed): php artisan vendor:publish --provider="Spatie\LaravelData\LaravelDataServiceProvider".
    • Configure IDE (e.g., PHPStorm) for Data class autocompletion.
  2. Validation migration:
    • Replace FormRequest classes with Data objects for validation.
    • Example:
      // Before: FormRequest
      public function rules(): array { return ['email' => 'required|email']; }
      
      // After: Data object
      class UserData extends Data {
          public function __construct(
              #[Validate('required|email')]
              public string $email,
          ) {}
      }
      
  3. API layer:
    • Replace API Resource classes with Data objects for responses.
    • Example:
      // Before: API Resource
      public function toArray($request): array { return ['email' => $this->email]; }
      
      // After: Data object
      class UserData extends Data {
          public function __construct(public string $email) {}
      }
      // Usage: UserData::from($user)->toArray()
      
  4. Frontend sync:
    • Generate TypeScript types: php artisan laravel-data:typescript.
    • Update frontend to use generated interfaces.
  5. Persistence:
    • Use WithData trait on Eloquent models for seamless data extraction.
    • Example:
      class User extends Model {
          use WithData;
          protected $dataClass = UserData::class;
      }
      // Usage: $user->getData() returns UserData
      

Operational Impact

Maintenance

  • Reduced boilerplate: Eliminates duplication across validation, API responses, and TypeScript definitions.
  • Centralized validation: Rules are defined once in Data objects, reducing maintenance overhead for shared logic.
  • Type safety: Catches errors at compile time (e.g., incorrect property types), reducing runtime bugs.
  • Documentation: Data objects serve as self-documenting contracts, improving onboarding for new developers.
  • Tooling:
    • IDE support: Autocompletion and refactoring tools work natively with Data classes.
    • Static analysis: PHPStan/Psalm can analyze Data objects for type correctness.
    • Testing: Easier to mock Data objects in tests (e.g., UserData::from([])).

Support

  • Troubleshooting:

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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai