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

Data Model Laravel Package

zero-to-prod/data-model

Reflection-based PHP data models that hydrate typed objects from arrays with a single from($data) call. Use #[Describe] attributes to define casting, validation, defaults, nullable/required rules, and assignments—keeping mapping logic predictable, readable, and verifiable.

View on GitHub
Deep Wiki
Context7

Product Decisions This Supports

  • Build vs. Buy: Buy – Eliminates the need to build custom DTO hydration logic, validation layers, or manual mapping utilities. Reduces technical debt by standardizing data transformation across the codebase.
  • Feature Roadmap:
    • API Layer: Standardize request/response DTOs for all endpoints, reducing boilerplate and improving maintainability.
    • Database Layer: Replace manual Eloquent model hydration with type-safe, declarative DataModel classes for queries/updates.
    • Form Handling: Centralize user input validation and transformation (e.g., sanitization, default values) in a single source of truth.
    • Microservices: Enforce consistent data contracts between services by defining DTOs with DataModel and validating payloads at boundaries.
  • Use Cases:
    • Type Safety: Replace runtime errors (e.g., array_key_exists failures) with compile-time checks via PHP attributes.
    • Validation: Consolidate scattered validation logic (e.g., Laravel’s validate() calls, custom if checks) into declarative Describe attributes.
    • Legacy Refactoring: Modernize monolithic classes with nested if-else hydration logic into modular, testable DataModel classes.
    • Performance: Reduce overhead of manual type casting (e.g., strval(), intval()) with optimized cast hooks.
    • Documentation: Auto-generate API specs or OpenAPI schemas from Describe attributes (via DataModelHelper or custom scripts).

When to Consider This Package

Adopt when:

  • Your team spends >20% of backend dev time on manual DTO hydration, validation, or data mapping (e.g., isset($data['x']) ? $obj->x = $data['x'] : ...).
  • You’re migrating from dynamic languages (e.g., JavaScript) or loosely typed systems (e.g., raw SQL/array-based apps) to PHP with strict typing.
  • API contracts are unstable or require frequent updates, and you need to future-proof against breaking changes.
  • Security is a priority: Centralized validation (e.g., pre/post hooks) reduces risk of missed edge cases in scattered logic.
  • You’re using Laravel and want to reduce dependency on Illuminate\Support\Collection or FormRequest validation classes.

Look elsewhere if:

  • Your data model is trivially simple (e.g., 1–2 properties with no validation/casting).
  • You’re in a high-performance context (e.g., real-time systems) where trait overhead is unacceptable (benchmark first).
  • Your team lacks PHP 8.0+ (attributes, union types) or composer dependency management.
  • You need database ORM integration (consider Laravel’s built-in Eloquent or Doctrine instead).
  • Your data is highly nested/recursive with custom serialization logic (e.g., JSON:API, GraphQL) that DataModel’s via attribute can’t handle.

How to Pitch It (Stakeholders)

For Executives:

"This package lets us write data transformation logic once and reuse it everywhere—cutting dev time by 30%+ and slashing bugs from manual mapping. For example:

  • API teams will spend less time debugging null values or type mismatches.
  • Frontend teams get self-documenting data contracts (e.g., #[Describe(['required' => true])] clearly marks mandatory fields).
  • We can enforce consistency across microservices by standardizing DTOs with DataModel attributes. It’s like Laravel’s Eloquent for data transformation—but for any class, any layer."

ROI:

  • Dev Velocity: Replace 50+ lines of hydration logic with 5 lines of Describe attributes.
  • Quality: Static analysis tools (PHPStan, Psalm) can now verify data contracts without runtime checks.
  • Scalability: Add new validation rules (e.g., regex, custom business logic) without touching existing code.

For Engineers:

"This is a drop-in replacement for manual DTO hydration that gives you:

  1. Type Safety: No more array_key_exists or isset checks—PHP’s type system + Describe attributes handle it.
  2. Centralized Validation: Move scattered if checks (e.g., in controllers, services) into declarative attributes on your model.
  3. Recursive Hydration: Automatically instantiate nested objects (e.g., User::from(['address' => [...]])Address object).
  4. Extensibility: Add custom logic via pre/post hooks or cast methods without subclassing.
  5. Zero Boilerplate: Compare:
    // Before (manual)
    $user = new User();
    $user->name = $data['name'] ?? '';
    $user->age = (int)($data['age'] ?? 0);
    if (!filter_var($data['email'] ?? '', FILTER_VALIDATE_EMAIL)) {
        throw new InvalidArgumentException('Invalid email');
    }
    $user->email = $data['email'] ?? '';
    
    // After (DataModel)
    class User {
        use \Zerotoprod\DataModel\DataModel;
        #[Describe(['required' => true])] public string $name;
        #[Describe(['cast' => 'intval'])] public int $age;
        #[Describe(['cast' => [self::class, 'validateEmail']])] public string $email;
    }
    $user = User::from($data); // Done.
    

Migration Path:

  • Start with critical DTOs (e.g., API request/response models).
  • Use DataModelHelper to batch-convert existing classes.
  • Replace Laravel FormRequests with DataModel-validated DTOs for cleaner controllers.

Trade-offs:

  • Learning Curve: Attributes and resolution order may require a workshop.
  • Tooling: Ensure your IDE (PHPStorm, VSCode) supports PHP 8+ attributes for full autocompletion.
  • Legacy Code: Gradual adoption via feature flags or wrapper classes."
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.
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
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata