Make sure you’ve installed Laravel Data before starting.
Creating your first data object
1
Create the PostData class
Let’s create a data object for blog posts. A post has a title, content, status, and publication date:
2
Define the PostStatus enum
Create a native PHP enum for the post status:
3
Create a PostData instance
You can create data objects like regular PHP objects:Or use the powerful
from method to create from various sources:Using data objects in controllers
1
Without Laravel Data (the old way)
Here’s a typical controller without Laravel Data:That’s a lot of boilerplate code!
2
With Laravel Data (the new way)
Laravel Data reduces this to just a few lines:Here’s what happens automatically:
- Laravel boots and routes to
PostController PostDatagenerates validation rules from property types- The request is validated automatically
- The
PostDataobject is created from validated request data - You receive a fully validated, type-safe data object
3
Inspect auto-generated validation rules
You can view the rules Laravel Data generates:Output:
Laravel Data automatically infers rules based on property types:
requiredfor non-nullable propertiesnullablefor nullable propertiesstring,numeric,boolean,arraybased on type hintsenumfor native enums
Adding validation attributes
Enhance auto-generated rules with validation attributes:date rule:
Transforming data objects
Data objects can be easily transformed into arrays or JSON:Nesting data objects
Create complex data structures by nesting data objects:The package automatically converts nested arrays into
PostData objects based on the docblock type hint.Working with lazy properties
Lazy properties are only included when explicitly requested, perfect for optimizing API responses:Generating blueprints
Create empty data structures for forms:Next steps
You’ve learned the basics! Laravel Data can do much more:Casts
Convert simple types to complex types
Transformers
Convert complex types to simple types
Validation
Deep dive into validation features
Collections
Work with collections of data objects
Eloquent Casting
Cast data objects in Eloquent models
TypeScript
Generate TypeScript definitions