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 validation, API resource, and Eloquent systems, reducing friction in adoption. It replaces repetitive boilerplate (e.g., Form Requests, API Resources, TypeScript definitions) with a single source of truth—Data objects.
  • Type safety: Enforces PHP types at runtime, reducing runtime errors and improving developer experience. The generated TypeScript definitions further bridge frontend/backend type consistency.
  • Modular design: Supports lazy properties, nested objects, collections, and morphing (e.g., polymorphic relationships), making it adaptable to complex domain models.
  • Validation-first approach: Integrates seamlessly with Laravel’s validation system, including custom rules, attributes, and conditional logic (e.g., required_if), while reducing manual rule duplication.

Integration Feasibility

  • Low friction for Laravel apps: Requires minimal setup (composer install + service provider registration). Works out-of-the-box with:
    • Form Requests: Replace Illuminate\Foundation\Http\FormRequest with Data objects for validation.
    • API Resources: Replace Illuminate\Http\Resources\Json\JsonResource with Data objects for serialization.
    • Eloquent Models: Cast attributes to Data objects for type-safe storage/retrieval.
    • Inertia/Livewire: Generate TypeScript types automatically for frontend integration.
  • Backward compatibility: Non-breaking changes in recent versions (e.g., PHP 8.4 support, Laravel 13). Migration path is straightforward for existing Laravel apps.
  • Tooling support: Works with Laravel’s testing utilities (e.g., create, factory), IDE autocompletion, and static analysis (PHPStan).

Technical Risk

  • Learning curve: Developers must adopt a new paradigm (Data objects instead of DTOs/Form Requests). Requires buy-in for team-wide adoption.
  • Validation edge cases: Complex conditional rules (e.g., required_with, prohibited_if) may need explicit overrides in the rules() method to avoid default behavior (e.g., skipping rules for nullable properties).
  • Performance overhead: Reflection-based validation and type casting add minimal runtime cost (~5–10% in benchmarks), but this is negligible for most applications.
  • Dependency conflicts: Rare but possible (e.g., Pest + PHP 8.4; resolved in v4.23.0). Test locally before production deployment.
  • TypeScript generation: Requires Node.js for laravel-data:typescript command. May need additional tooling (e.g., Vite, Webpack) for frontend projects.

Key Questions

  1. Adoption scope:
    • Will this replace all Form Requests/API Resources, or only new features?
    • How will existing validation logic (e.g., custom rules in AppServiceProvider) migrate to Data objects?
  2. Team readiness:
    • Is the team comfortable with PHP’s type system and reflection?
    • Are developers familiar with Laravel’s validation attributes (e.g., #[Rule('unique:users,email')])?
  3. Frontend integration:
    • How will TypeScript types be consumed (e.g., Inertia, REST APIs, GraphQL)?
    • Will the team use the laravel-data:typescript command or a custom solution?
  4. Testing impact:
    • How will existing tests (e.g., feature tests with FormRequest assertions) adapt to Data objects?
    • Are there plans to use Data objects in factories or seeders?
  5. Legacy systems:
    • How will non-Laravel services (e.g., legacy PHP, microservices) interact with Data objects?
    • Are there plans to expose Data objects via APIs (e.g., JSON:API, GraphQL)?

Integration Approach

Stack Fit

  • Laravel-centric: Optimized for Laravel 10/11/12/13, with support for:
    • Validation: Replaces FormRequest validation with type-safe Data objects.
    • APIs: Replaces JsonResource with Data objects for serialization (supports lazy loading, pagination, and relationships).
    • Eloquent: Casts model attributes to Data objects for type safety.
    • Frontend: Generates TypeScript interfaces for Inertia, Livewire, or REST APIs.
  • Complementary tools:
    • Livewire 4: Supports defer groups for lazy-loaded properties.
    • Inertia v3: Fallback to OptionalProp for compatibility.
    • Pest/Testing: Works with Laravel’s testing helpers (e.g., create, assertValid).
  • Non-Laravel PHP: Can be used standalone (e.g., in CLI apps) for typed data transfer, but loses Laravel-specific features (e.g., validation, Eloquent casts).

Migration Path

  1. Pilot phase:
    • Start with a single feature/module (e.g., user registration) to test Data objects alongside existing FormRequest/JsonResource.
    • Replace one component at a time (e.g., API resource → Data object).
  2. Validation migration:
    • Move validation rules from FormRequest to Data object properties (using PHP attributes or rules() method).
    • Example:
      // Before (FormRequest)
      public function rules(): array {
          return ['email' => 'required|email'];
      }
      
      // After (Data object)
      class UserData extends Data {
          #[Rule('required|email')]
          public string $email;
      }
      
  3. API layer:
    • Replace JsonResource with Data objects for responses. Use toArray() or toJson() methods.
    • Example:
      // Before (JsonResource)
      public function toArray($request) {
          return ['email' => $this->user->email];
      }
      
      // After (Data object)
      class UserResponse extends Data {
          public function __construct(
              public string $email,
          ) {}
      }
      
  4. Frontend sync:
    • Run php artisan laravel-data:typescript to generate TypeScript interfaces.
    • Update frontend code to use the generated types (e.g., Inertia page props).
  5. Eloquent integration:
    • Cast model attributes to Data objects using HasData trait or custom casts.
    • Example:
      use Spatie\LaravelData\Casts\Data;
      
      class User extends Model {
          protected $casts = [
              'profile' => Data::class,
          ];
      }
      

Compatibility

  • Laravel versions: Tested on 10–13. Drop-in for 10/11; newer features (e.g., Livewire 4) require v4.20+.
  • PHP versions: Supports 8.1+ (dropped 8.1 in v4.20.0). Use 8.2+ for full feature set (e.g., enums, attributes).
  • Dependencies:
    • Conflicts resolved in v4.23.0 (e.g., Pest + PHP 8.4).
    • Avoid mixing with other reflection-heavy packages (e.g., spatie/laravel-activitylog).
  • Database: No direct impact, but validation rules can enforce database constraints (e.g., #[DatabaseConstraint('unique')]).

Sequencing

  1. Phase 1 (Validation):
    • Replace FormRequest with Data objects for new features.
    • Update existing validation logic to use PHP attributes or rules() methods.
  2. Phase 2 (API Layer):
    • Replace JsonResource with Data objects for responses.
    • Generate TypeScript types and update frontend.
  3. Phase 3 (Eloquent):
    • Cast model attributes to Data objects.
    • Update queries/factories to work with Data objects.
  4. Phase 4 (Frontend):
    • Full TypeScript integration (Inertia/Livewire).
    • Deprecate manual DTOs in favor of generated types.

Operational Impact

Maintenance

  • Reduced boilerplate: Eliminates duplicate validation/API resource logic, lowering maintenance overhead.
  • Centralized validation: Rules are defined once in Data objects, reducing inconsistencies.
  • Type safety: Catches errors at compile time (PHP) and runtime (TypeScript), reducing bugs.
  • Dependency updates:
    • Spatie releases are frequent (~monthly). Monitor for breaking changes (e.g., PHP 8.4+ features).
    • Pin major versions in composer.json (e.g., ^4.23) to avoid surprises.
  • Debugging:
    • Use dd($dataObject) to inspect structure.
    • Validation errors include property paths (e.g., user.profile.email).
    • Enable Data::enableDebugMode() for detailed logs.

Support

  • Documentation: Comprehensive Spatie docs with examples for validation, API resources, and TypeScript.
  • Community: Active GitHub repo (1.8k stars, 1773+ forks) with responsive maintainers.
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony