Skip to main content
This quickstart guides you through creating a blog application with type-safe data objects. You’ll learn the core functionality of Laravel Data by building real examples.
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:
Store data objects in app/Data/PostData.php or use php artisan make:data Post to generate the file automatically.
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:
  1. Laravel boots and routes to PostController
  2. PostData generates validation rules from property types
  3. The request is validated automatically
  4. The PostData object is created from validated request data
  5. 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:
  • required for non-nullable properties
  • nullable for nullable properties
  • string, numeric, boolean, array based on type hints
  • enum for native enums

Adding validation attributes

Enhance auto-generated rules with validation attributes:
Now the validation rules include the date rule:
Laravel Data provides dozens of validation attributes like Email, Max, Min, Url, and more.

Transforming data objects

Data objects can be easily transformed into arrays or JSON:

Nesting data objects

Create complex data structures by nesting data objects:
Create nested data objects from arrays:
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:
Control what’s included in the output:

Generating blueprints

Create empty data structures for forms:
With default values:

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