Validation Rules That Can See the Rest of the Form: DataAwareRule, ValidatorAwareRule and Rule::forEach

Write a Laravel custom validation rule that reads other fields with DataAwareRule, reports against the right attribute, and varies per array row with forEach.

Steven Richardson
Steven Richardson
· 10 min read

Open StoreSubscriptionRequest::rules() on any application that's been live for two years. Forty lines, half of them Rule::when() closures, three of them copy-pasted into the update request. The reason they live there and not in app/Rules is simple: a plain rule object can't see the rest of the form, so anything conditional has nowhere else to go. Here's how DataAwareRule, ValidatorAwareRule and Rule::forEach() close that gap, verified against Laravel v13.6.0.

Generate a plain rule object and find its blind spot#

Scaffold a rule with Artisan. Laravel generates a class implementing Illuminate\Contracts\Validation\ValidationRule, which has one method — validate(string $attribute, mixed $value, Closure $fail): void. The older Rule contract with its passes()/message() pair is deprecated, and so is InvokableRule; new rules should implement ValidationRule.

php artisan make:rule VatNumberRequired --no-interaction

That signature is the whole problem. The rule knows its attribute name and its value, and nothing about the payload it arrived in. A VAT number that's only required for EU business customers on an annual plan needs country and plan, so the logic stays in the request as a closure — and the moment a second request needs the same rule, it gets pasted.

// app/Rules/VatNumberRequired.php — the blind version
public function validate(string $attribute, mixed $value, Closure $fail): void
{
    // No way to reach $request->country from here.
    if ($value === null) {
        $fail('A VAT number is required.');
    }
}

Read the rest of the payload with DataAwareRule#

Implement Illuminate\Contracts\Validation\DataAwareRule and Laravel hands the rule the full data under validation through setData() before it calls validate(). In Validator::validateUsingCustomRule() the order is fixed: setValidator() first if the rule implements ValidatorAwareRule, then setData(), then the rule runs. So $this->data is always populated by the time you need it.

Two details matter. The data you receive is the validator's data, which means it is post-prepareForValidation() — anything you merge or normalise there is visible. And it is the whole payload, including keys with no rules attached, so reach for data_get() rather than assuming a shape.

<?php

declare(strict_types=1);

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\DataAwareRule;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Arr;

class VatNumberRequired implements DataAwareRule, ValidationRule
{
    /** Fire even when the attribute is missing or empty. */
    public bool $implicit = true;

    /** @var array<string, mixed> */
    protected array $data = [];

    public function __construct(protected VatNumberValidator $vies) {}

    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $country = data_get($this->data, 'country');
        $plan = data_get($this->data, 'plan');

        // Only EU business customers on the annual plan owe us a VAT number.
        if ($plan !== 'annual' || ! in_array($country, self::EU, strict: true)) {
            return;
        }

        if (blank($value)) {
            $fail('validation.vat.required')->translate();

            return;
        }

        if (! $this->vies->isValidFor($value, $country)) {
            $fail('validation.vat.invalid')->translate([':country' => $country]);
        }
    }

    /** @param array<string, mixed> $data */
    public function setData(array $data): static
    {
        $this->data = $data;

        return $this;
    }
}

That public bool $implicit = true line is not decoration. By default Laravel skips a rule when the attribute is absent or empty, so a "required when…" rule never runs on the exact input it exists to catch. php artisan make:rule VatNumberRequired --implicit generates the property for you, and InvokableValidationRule::make() wraps the rule in an anonymous class implementing ImplicitRule when it sees it.

The request collapses to a line:

public function rules(): array
{
    return [
        'country' => ['required', 'string', 'size:2'],
        'plan' => ['required', Rule::in(['monthly', 'annual'])],
        'vat_number' => [app(VatNumberRequired::class)],
    ];
}

Constructor injection is the reason this beats Validator::extend(). An extension is a closure registered on a service provider with no container story; a rule object takes its dependencies in the constructor, which is also what makes it testable without booting a request. Value objects fit neatly here too — if country is already a typed object rather than a loose string, the rule reads better; I covered that pattern in PHP readonly classes as value objects.

Report against the right field with ValidatorAwareRule#

Sometimes the failing field is not the field being validated. A rule on start_date that compares against end_date should put its error where the user will see it. The simplest route is the second argument to $fail(): $fail('end_date', 'The end date must be after the start date.') keys the message to end_date, because CreatesPotentiallyTranslatedStrings switches to $this->messages[$attribute] = $message as soon as you pass a message explicitly.

ValidatorAwareRule is for the cases that need more — reading what has already failed, or adding errors directly. Implement it, store the validator, and keep what you do with it narrow.

<?php

declare(strict_types=1);

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\DataAwareRule;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Contracts\Validation\ValidatorAwareRule;
use Illuminate\Validation\Validator;

class BookingWindowIsValid implements DataAwareRule, ValidationRule, ValidatorAwareRule
{
    /** @var array<string, mixed> */
    protected array $data = [];

    protected Validator $validator;

    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        // Don't pile on: if end_date already failed its own rules, stay quiet.
        if ($this->validator->errors()->has('end_date')) {
            return;
        }

        $end = data_get($this->data, 'end_date');

        if ($end !== null && strtotime($end) <= strtotime((string) $value)) {
            // Two-argument $fail keys the message to end_date, not start_date.
            $fail('end_date', 'validation.booking.window')->translate();
        }
    }

    /** @param array<string, mixed> $data */
    public function setData(array $data): static
    {
        $this->data = $data;

        return $this;
    }

    public function setValidator(Validator $validator): static
    {
        $this->validator = $validator;

        return $this;
    }
}

Resist $validator->errors()->add() inside a rule. It bypasses Laravel's placeholder replacement, so :attribute and friends arrive raw in the message bag, and it fires regardless of whether the rule actually failed. Use it to read state; use $fail() to write it.

Vary the rules per row with Rule::forEach#

items.*.quantity applies one rule set to every row, which is wrong the moment rows differ. Rule::forEach() takes a callback and returns a NestedRules instance; the callback is invoked per matching item with ($value, $attribute, $data, $context), where $value is that item and $attribute is the fully expanded path such as items.2. Return the rules for that row and Laravel compiles them against the real key.

use Illuminate\Validation\Rule;

public function rules(): array
{
    return [
        'items' => ['required', 'array', 'min:1'],
        'items.*' => Rule::forEach(function (mixed $item, string $attribute) {
            // $attribute is 'items.0', 'items.1', ... — the real path, not the wildcard.
            $type = data_get($item, 'type');

            return [
                'type' => ['required', Rule::in(['physical', 'digital', 'service'])],
                'quantity' => match ($type) {
                    // A licence key is one per order; stock is capped by the warehouse.
                    'digital' => ['required', 'integer', 'size:1'],
                    'service' => ['required', 'integer', 'between:1,10'],
                    default => ['required', 'integer', 'min:1', new WithinStock($item)],
                },
            ];
        }),
    ];
}

Errors come back keyed by the expanded path — items.1.quantity — so a Livewire or Precognition front end can place them against the right row with no extra mapping. If you're wiring this into a form that validates as the user types, the same rules run unchanged through Precognition's live form validation.

Move the messages into translation files#

The $fail closure returns a PotentiallyTranslatedString. Call ->translate() on it and the string is treated as a translation key, with the replacements array passed straight to the translator. A rule used in six requests then needs one copy of its wording.

// lang/en/validation.php
'vat' => [
    'required' => 'A VAT number is required for annual business plans in the EU.',
    'invalid' => 'That VAT number was rejected by the :country registry.',
],
'booking' => [
    'window' => 'The end date must be after the start date.',
],

Keep the chain in one statement. The message is written to the bag by the object's destructor, so $fail('validation.vat.invalid')->translate([':country' => $country]); registers the translated string, while assigning the return value to a long-lived variable delays the write until that variable goes out of scope.

Test the rule in isolation and through the request#

A rule object is a plain class, so the unit test is a constructor call, a setData() call and a spy for $fail. That is the entire payoff over a closure buried in rules().

<?php

use App\Rules\VatNumberRequired;

it('requires a VAT number for EU annual plans', function (): void {
    $failed = [];

    $rule = new VatNumberRequired(new FakeVatNumberValidator);
    $rule->setData(['country' => 'DE', 'plan' => 'annual']);

    $rule->validate('vat_number', null, function (string $message) use (&$failed) {
        $failed[] = $message;
    });

    expect($failed)->toHaveCount(1);
});

it('stays quiet for monthly plans', function (): void {
    $failed = [];

    $rule = new VatNumberRequired(new FakeVatNumberValidator);
    $rule->setData(['country' => 'DE', 'plan' => 'monthly']);

    $rule->validate('vat_number', null, fn (string $m) => $failed[] = $m);

    expect($failed)->toBeEmpty();
});

The closure above stands in for Laravel's real $fail, which returns a PotentiallyTranslatedString; if your rule chains ->translate(), return a string-backed double or assert through the HTTP layer instead. One feature test per rule covers the wiring — that the rule is actually attached, and that it is implicit when it needs to be:

it('rejects an EU annual signup with no VAT number', function (): void {
    $this->postJson('/subscriptions', [
        'country' => 'DE',
        'plan' => 'annual',
    ])->assertJsonValidationErrors(['vat_number']);
});

it('keys per-row errors to the expanded path', function (): void {
    $this->postJson('/orders', [
        'items' => [
            ['type' => 'digital', 'quantity' => 4],
        ],
    ])->assertJsonValidationErrors(['items.0.quantity']);
});

If those assertions start repeating across a suite, they're a good candidate for custom Pest expectations in your domain language.

Gotchas and Edge Cases#

Rule::forEach() is quadratic on large lists. ValidationRuleParser::explodeWildcardRules() compiles the nested rules once per matching key, and each compile runs Arr::undot() over the whole gathered payload again. On v13.6.0 a 2,000-item list takes roughly ten seconds, almost all of it in rule compilation — laravel/framework#62689 has the benchmarks and a fix, but it was still open at the time of writing. If you validate long lists today, plain items.*.field wildcards do not have this problem.

$implicit is opt-in and easy to forget. Without it, the rule never runs for a missing or blank attribute, which is silent — the request passes and you find out in production.

setData() gives you the validator's data, not the request. Fields you strip in prepareForValidation() are gone, and route parameters were never there. Inject what you need instead of reaching for request() inside the rule.

Rules run in order, and a rule object runs even after earlier rules on the same attribute failed unless you add bail. If your rule assumes $value is already an integer because integer precedes it in the array, add bail or type-check defensively.

One rule instance is reused across every matching attribute. A rule object attached to items.*.sku is the same object for every row, so anything you cache in a property leaks between rows. Keep rules stateless apart from setData()/setValidator().

Wrapping Up#

Start with the rule you've copy-pasted most, make it DataAware, and delete both copies from your requests. The signature cost is one method; the payoff is a named class with a unit test. If your validation lives in Livewire rather than FormRequests, the same objects drop straight into Livewire 4 Form Objects with #[Validate], and multi-step flows get the per-step treatment in this wizard walkthrough.

FAQ#

How do I access other fields in a Laravel custom validation rule?

Implement the Illuminate\Contracts\Validation\DataAwareRule interface on your rule class and add a setData(array $data) method that stores the array. Laravel calls it with the full data under validation immediately before validate() runs, so you can read any other field from the stored array. Use data_get() rather than direct array access, because the payload may not contain the key you expect.

What is DataAwareRule in Laravel?

DataAwareRule is a one-method contract in Illuminate\Contracts\Validation that signals a rule needs the rest of the data under validation. Its only method is setData(array $data), which the validator calls before running the rule. It exists because the ValidationRule contract deliberately passes only the attribute, the value and a $fail callback.

How do I validate each item of an array differently?

Attach Rule::forEach() to the wildcard attribute and return a different rule set per item from the callback. The callback receives the item's value and its fully expanded attribute path, so you can branch on a field within the row — a digital line item can get different quantity rules from a physical one. Errors are keyed by the expanded path, such as items.2.quantity.

When should I use a rule object instead of a closure?

Use a rule object whenever the rule has dependencies, is used in more than one request, or is worth testing on its own. Closures are fine for a one-off check that reads a single value and never moves. Rule objects are also the right answer over Validator::extend(), because they can be constructor-injected from the container and their message lives with their logic.

How do I unit test a Laravel validation rule?

Instantiate the rule directly, call setData() if it implements DataAwareRule, then call validate() with an attribute name, a value and a closure that records the failure message. Assert on what that closure collected. Pair it with one feature test that posts to the route and uses assertJsonValidationErrors() to prove the rule is actually attached.

How do I add a custom validation message to a rule object?

Pass the message string to the $fail closure inside validate(). For translations, pass a translation key and chain ->translate() on the returned PotentiallyTranslatedString, optionally with a replacements array. To attach the error to a different field, call the two-argument form: $fail('end_date', 'validation.booking.window')->translate().

Steven Richardson
Steven Richardson

CTO at Digitonic. Writing about Laravel, architecture, and the craft of leading software teams from the west coast of Scotland.