Build your first Laravel Data object in minutes with this step-by-step guide
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.
Let’s create a data object for blog posts. A post has a title, content, status, and publication date:
use Spatie\LaravelData\Data;class PostData extends Data{ public function __construct( public string $title, public string $content, public PostStatus $status, public ?CarbonImmutable $published_at ) { }}
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:
enum PostStatus: string{ case draft = 'draft'; case published = 'published'; case archived = 'archived';}
3
Create a PostData instance
You can create data objects like regular PHP objects:
$post = new PostData( 'Hello laravel-data', 'This is an introduction post for the new package', PostStatus::published, CarbonImmutable::now());
Or use the powerful from method to create from various sources:
$post = PostData::from([ 'title' => 'Hello laravel-data', 'content' => 'This is an introduction post for the new package', 'status' => PostStatus::published, 'published_at' => CarbonImmutable::now(),]);
Enhance auto-generated rules with validation attributes:
use Spatie\LaravelData\Attributes\Validation\Date;class PostData extends Data{ public function __construct( public string $title, public string $content, public PostStatus $status, #[Date] public ?CarbonImmutable $published_at ) { }}
Create complex data structures by nesting data objects:
class AuthorData extends Data{ /** * @param array<int, PostData> $posts */ public function __construct( public string $name, public array $posts ) { }}
Create nested data objects from arrays:
$author = AuthorData::from([ 'name' => 'Ruben Van Assche', 'posts' => [ [ 'title' => 'Hello laravel-data', 'content' => 'Introduction post', 'status' => PostStatus::published, ], [ 'title' => 'What is a data object', 'content' => 'How does it work', 'status' => PostStatus::draft, ], ],]);
The package automatically converts nested arrays into PostData objects based on the docblock type hint.
Lazy properties are only included when explicitly requested, perfect for optimizing API responses:
use Spatie\LaravelData\Lazy;class AuthorData extends Data{ public function __construct( public string $name, public Collection|Lazy $posts ) { } public static function fromModel(Author $author): self { return new self( $author->name, Lazy::create(fn() => PostData::collect($author->posts)) ); }}
Control what’s included in the output:
$author = AuthorData::from($authorModel);return $author;// Result:{ "name": "Ruben Van Assche"}