Get expert guidance in a few days with a Laravel code review

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
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

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

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
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
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
Lucky Media logo

Lucky Media

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

Lucky Media
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

The latest

View all →
Laravel Announces Official AI SDK for Building AI-Powered Apps image

Laravel Announces Official AI SDK for Building AI-Powered Apps

Read article
`hasMany()` Collection Method in Laravel 12.50.0 image

`hasMany()` Collection Method in Laravel 12.50.0

Read article
Mask Sensitive Eloquent Attributes on Retrieval in Laravel image

Mask Sensitive Eloquent Attributes on Retrieval in Laravel

Read article
Encrypt Files in Laravel with AES-256-GCM and Memory-Efficient Streaming image

Encrypt Files in Laravel with AES-256-GCM and Memory-Efficient Streaming

Read article
Statamic 6 Is Officially Released image

Statamic 6 Is Officially Released

Read article
Livewire 4 and Blade Improvements in Laravel VS Code Extension v1.5.0 image

Livewire 4 and Blade Improvements in Laravel VS Code Extension v1.5.0

Read article