- How do I replace a Laravel Form Request with a Data object?
- Extend `Data` and define properties with type hints in the constructor. Use `fromRequest()` to validate and populate the object from incoming requests. For example, replace `CreatePostRequest` with `PostData::fromRequest($request)` to handle validation and data extraction in one step.
- Can I use Data objects with Laravel API Resources?
- Yes. Data objects can be transformed into API resources using `toArray()` or `toJson()`. For example, extend `JsonResource` and pass a Data object to its constructor. The package handles serialization automatically, reducing boilerplate.
- What Laravel versions does spatie/laravel-data support?
- The package supports Laravel 9.x and 10.x. Check the [GitHub repository](https://github.com/spatie/laravel-data) for the latest compatibility details, as minor updates may align with new Laravel releases.
- How do lazy properties work in Data objects?
- Lazy properties defer transformation until explicitly accessed. Use `Lazy::inertiaDeferred()` for Inertia.js or `Lazy::jsonDeferred()` for API responses. This reduces payload size and improves performance by loading only requested fields.
- Does this package generate TypeScript types automatically?
- Yes, use Spatie’s `typescript-transformer` to generate TypeScript interfaces from your Data objects. Run `php artisan data:generate-typescript` to create `.d.ts` files. This ensures frontend types stay in sync with your backend data structure.
- Will Data objects impact performance in production?
- Reflection-based analysis adds minimal overhead. Mitigate this by running `php artisan data:cache-structures` in production to cache metadata. For high-traffic apps, ensure the cache (e.g., Redis) is optimized for low latency.
- Can I use Data objects with Eloquent models?
- Absolutely. Cast model attributes to Data objects using `hasOne` or `morphTo` relationships. For example, define `$casts = ['metadata' => SongData::class]` in your model to automatically convert attributes to typed Data objects.
- How do I test Data objects in Laravel?
- Test Data objects like regular classes. Use `Data::from()` to create instances from arrays or models, then assert properties. For validation, pass invalid data and verify exceptions. Mock `typescript-transformer` if testing TypeScript generation.
- Are there alternatives to spatie/laravel-data for typed data objects?
- Yes, consider `spatie/laravel-arrayable` for simpler serialization or `symfony/serializer` for broader use cases. However, `laravel-data` uniquely combines validation, lazy loading, and TypeScript generation in a Laravel-native way.
- How do I handle nested Data objects or relationships?
- Define nested Data objects as properties in your class. For relationships, use `Data::from()` to convert associated models. For example, `public function __construct(public UserData $author) {}` automatically handles nested validation and serialization.