Intro

Mastering Laravel Data

Published

25 Jun, 2025

Tag

Backend Development

Blog

Laravel is one of the most popular PHP frameworks used for building scalable and maintainable web applications. While Laravel already provides powerful tools like Eloquent ORM and Query Builder, developers often need an extra layer to structure their application’s data handling more cleanly—this is where Laravel Data (from spatie/laravel-data) comes into play.

In this post, we’ll cover:

  • What Laravel Data is
  • How to set it up
  • A real-world example
  • Why and when you should use it

💡 What is Laravel Data?

Laravel Data is a package developed by Spatie that helps you create data transfer objects (DTOs) in Laravel. It’s a clean and efficient way to manage the transformation and validation of data between layers (e.g., from a request to a model or API response).

Instead of juggling arrays or manually mapping fields, you define strict typed data classes.

⚙️ Setting Up Laravel Data

🔹 Step 1: Install the Package

composer require spatie/laravel-data

🔹 Step 2: (Optional) Publish Config

php artisan vendor:publish --tag=laravel-data-config

🛠 Real-World Example: Blog Post API

Scenario:

You are building an API endpoint to create blog posts. You want clean input validation, transformation, and return responses—all handled using Laravel Data.

✅ Step 1: Create a DTO for Request Data

php artisan make:data BlogPostData

namespace App\Data;

use Spatie\LaravelData\Data;

class BlogPostData extends Data
{
   public function __construct(
       public string $title,
       public string $content,
       public ?string $category = null,
   ) {}
}

✅ Step 2: Use DTO in Form Request or Controller

You can now use this DTO directly in your controller:

use App\Data\BlogPostData;
use App\Models\Blog;

public function store(BlogPostData $data)
{
   $blog = Blog::create($data->all());

   return response()->json([
       'message' => 'Blog post created successfully!',
       'data' => $blog,
   ]);
}

You can also apply rules to it like so:

class BlogPostData extends Data
{
   public static function rules(): array
   {
       return [
           'title' => ['required', 'string'],
           'content' => ['required', 'string'],
       ];
   }
}

🔁 Optional: Returning Clean API Responses

Use the same DTO to return structured and transformed responses:

return BlogPostData::from($blog);

This returns a clean, typed, and consistent API structure without exposing model internals like created_at, updated_at, or hidden fields.

🎯 Benefits of Using Laravel Data

✅ 1. Cleaner Code Architecture

DTOs force you to define a data structure, avoiding messy arrays or deep coupling between models and views.

✅ 2. Improved Validation

You can define validation rules directly inside the DTO—great for API request classes.

✅ 3. Automatic Transformation

You can easily transform enums, nested data, date formatting, etc.

✅ 4. Great for APIs

If you're building a RESTful API or working with external systems, DTOs help keep your input and output consistent and safe.

✅ 5. Better Testability

Since logic is abstracted into DTOs, it becomes easier to unit test the business layer separately.

🧪 Final Thoughts

Laravel Data is not mandatory for every project—but when you start dealing with complex inputs, nested structures, APIs, or large-scale apps, it becomes invaluable.

Whether you're building a CMS, e-commerce, or SaaS platform, using spatie/laravel-data will help you build cleaner, more maintainable, and well-structured Laravel applications.