Validate Controller Requests with the Laravel Data Package

Published on by

Validate Controller Requests with the Laravel Data Package image

The Laravel Data package has many incredible features for working with data objects in Laravel applications. Data objects are rich, typed, and highly configurable objects that can double as API resources, form requests, TypeScript definitions, and more.

One interesting thing I initially didn't realize, but later discovered, was the ability to use Laravel Data objects for Controller request validation. In fact, data objects have powerful validation that you can use in a variety of ways. Let's take a simple ArticleData object as an example:

namespace App\Data;
 
use Carbon\CarbonImmutable;
use Spatie\LaravelData\Data;
 
class ArticleData extends Data
{
public function __construct(
public string $title,
public string $content,
public ?string $description = null,
public ?CarbonImmutable $published_at = null,
public ?CarbonImmutable $created_at = null,
public ?CarbonImmutable $updated_at = null,
) {}
}

You wouldn't know by looking at it, but this object infers validation rules from this data object:

App\Data\ArticleData::validate([])
 
// Illuminate\Validation\ValidationException The title field is required. (and 1 more error).

We won't go over every facet of validation in Laravel Data, but the validation docs will walk you through everything. Validation is highly configurable and integrates nicely with Laravel.

Using Laravel Data to Validate a Request

Let's take our article example, and use the object to validate creating a record in the database via our fictitious Article controller:

namespace App\Http\Controllers;
 
use App\Data\ArticleData;
use App\Models\Article;
 
class CreateArticleController extends Controller
{
public function __invoke(ArticleData $data)
{
$article = Article::create([
'title' => $data->title,
'content' => $data->content,
'description' => $data->description,
'published_at' => $data->published_at,
]);
 
return response()->json(ArticleData::from($article), 201, [
'Location' => route('article.show', $article),
]);
}
}

If we wrote a test for this to trigger the default validation, it would look something like the following:

#[Test]
public function it_validates_article_creation()
{
$response = $this->postJson('/article', []);
 
$response->assertStatus(422);
$response->assertJsonValidationErrors([
'title' => 'The title field is required.',
'content' => 'The content field is required.',
]);
}

Let's say that we wanted to allow the published_at request parameter optionally, but also want to make sure the published_at date format matched what we expected:

// app/Data/ArticleData.php
use Spatie\LaravelData\Attributes\Validation\DateFormat;
 
 
#[DateFormat(DATE_ATOM)]
public ?CarbonImmutable $published_at = null,

If we sent the published_at field with an invalid format, we would get back the following JSON validation errors:

{
"message": "The title field is required. (and 2 more errors)",
"errors": {
"title": [
"The title field is required."
],
"content": [
"The content field is required."
],
"published_at": [
"The published at field must match the format Y-m-d\\TH:i:sP."
]
}
}

Let's say we wanted the validation message to read differently. Like Laravel's Request objects, you can define a messages() method:

public static function messages(): array
{
return [
'published_at.date_format' => 'The entity event timestamp must be in the ISO 8601 format (e.g., 2025-05-14T19:32:31+00:00).',
];
}

The messages array follows the same patterns that Laravel request objects, supports nested objects, and more. Here's what our updated message would look like for the published_at field:

{
"message": "...",
"errors": {
"published_at": [
"The entity event timestamp must be in the ISO 8601 format (e.g., 2025-05-14T19:32:31+00:00)."
]
}
}

Learn More

To learn more about using validation with the Laravel Data package, I check out the advanced usage section for Using validation attributes and reference the Validation attributes page for all the available attributes you can use with validation.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $9500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell

The latest

View all →
Community Laravel Extension for Zed image

Community Laravel Extension for Zed

Read article
Advanced Eloquent Query Filtering with Filterable image

Advanced Eloquent Query Filtering with Filterable

Read article
Bulk Job Dispatching with Bus::bulk() in Laravel 13.13 image

Bulk Job Dispatching with Bus::bulk() in Laravel 13.13

Read article
Audit Laravel Apps for Security Issues with Checkpoint image

Audit Laravel Apps for Security Issues with Checkpoint

Read article
In-Memory Eloquent Models with Truffle image

In-Memory Eloquent Models with Truffle

Read article
Detect and Resolve Laravel Schema Drift with MigrAlign image

Detect and Resolve Laravel Schema Drift with MigrAlign

Read article