4,000 emails/month for free | Mailtrap sends real emails now!

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
Laravel Cloud

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

Visit Laravel Cloud
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
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
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
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
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
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
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 →
FluentVox: AI Text-to-Speech for Laravel with Voice Cloning and GPU Acceleration image

FluentVox: AI Text-to-Speech for Laravel with Voice Cloning and GPU Acceleration

Read article
Laravel Boost v1.8.10 Released With New AI Prompts and Livewire v4 Support image

Laravel Boost v1.8.10 Released With New AI Prompts and Livewire v4 Support

Read article
Statamic 6 Beta Now Available image

Statamic 6 Beta Now Available

Read article
Everything new in Livewire 4 image

Everything new in Livewire 4

Read article
Cache Without Overlapping in Laravel 12.47.0 image

Cache Without Overlapping in Laravel 12.47.0

Read article
Going Real-Time with Reverb - Laravel In Practice EP17 image

Going Real-Time with Reverb - Laravel In Practice EP17

Read article