Move validation out of controllers, form requests, and ad hoc validators into reusable ruleset objects.
This package provides a Ruleset base class that can validate either:
- any object implementing
ValidatesWithRuleset - a regular
Illuminate\Http\Request
That makes it useful for DTOs, actions, domain objects, and controllers that want FormRequest-style validation without requiring a dedicated FormRequest subclass for every workflow.
Install the package via Composer:
composer require craftcms/laravel-ruleset-validationThe package uses Laravel package auto-discovery, so no manual service provider registration is required.
For request-backed validation, this package intentionally follows Laravel's FormRequest validation model as closely as possible.
Read the Laravel documentation for the validation lifecycle, authorization, hooks, validated input, redirects, error bags, and Precognition:
Laravel Form Request Validation
Laravel Working With Validated Input
If you know how to write a FormRequest, you already know how to write a Ruleset.
The main difference from FormRequest is not the validation API, but where the validation logic can live.
Create a class that implements ValidatesWithRuleset, add the HasRuleset trait, then point it at a ruleset.
<?php
namespace App\Data;
use App\Rulesets\CreatePostRuleset;
use CraftCms\RulesetValidation\Attributes\Ruleset;
use CraftCms\RulesetValidation\Concerns\HasRuleset;
use CraftCms\RulesetValidation\Contracts\ValidatesWithRuleset;
#[Ruleset(CreatePostRuleset::class)]
class CreatePostData implements ValidatesWithRuleset
{
use HasRuleset;
public function __construct(
public string $title,
public ?string $slug = null,
public ?string $body = null,
) {}
public function validationData(): array
{
return [
'title' => $this->title,
'slug' => $this->slug,
'body' => $this->body,
];
}
}Then define the ruleset:
<?php
namespace App\Rulesets;
use CraftCms\RulesetValidation\Ruleset;
class CreatePostRuleset extends Ruleset
{
public function rules(): array
{
return [
'title' => ['required', 'string', 'max:255'],
'slug' => ['nullable', 'string', 'max:255'],
'body' => ['nullable', 'string'],
];
}
}Validate the object anywhere in your application:
$data = new CreatePostData(
title: 'Rulesets are nice',
slug: 'rulesets-are-nice',
body: '...',
);
$validated = $data->ruleset->validate();You can also validate only a subset of attributes:
$validated = $data->ruleset
->only(['title', 'slug'])
->validate();And if you need a non-throwing flow for object-backed validation:
$ruleset = $data->ruleset->only(['title']);
if ($ruleset->fails()) {
$validator = $ruleset->getValidator();
// Inspect $validator->errors()
}If you want FormRequest behavior without a FormRequest subclass, type-hint the ruleset in your controller action and let Laravel resolve it.
<?php
namespace App\Rulesets;
use CraftCms\RulesetValidation\Ruleset;
class StorePostRuleset extends Ruleset
{
public function rules(): array
{
return [
'title' => ['required', 'string', 'max:255'],
'body' => ['nullable', 'string'],
];
}
}use App\Rulesets\StorePostRuleset;
class PostController
{
public function store(StorePostRuleset $ruleset)
{
$validated = $ruleset->validate();
// ...
}
}If you need to construct one manually, you can instantiate the ruleset directly:
$ruleset = new StorePostRuleset(subject: $request);Rulesets include a lightweight scenario API that FormRequest does not provide.
use Illuminate\Validation\Rule;
class PostRuleset extends Ruleset
{
public const SCENARIO_DRAFT = 'draft';
public function rules(): array
{
return [
'title' => [
Rule::requiredIf($this->inScenarios(self::SCENARIO_DRAFT)),
'string',
'max:255'
],
];
}
}$validated = $data->ruleset
->useScenario(PostRuleset::SCENARIO_DRAFT)
->validate();If you only want to switch scenarios for one operation, use withScenario(). The previous scenario is restored after the callback returns or throws.
$validated = $data->ruleset->withScenario(
PostRuleset::SCENARIO_DRAFT,
fn () => $data->ruleset->validate(),
);Available helpers:
useScenario(string $scenario): staticwithScenario(string $scenario, Closure $callback): mixedgetScenario(): stringinScenarios(string ...$scenarios): bool
When injecting a ruleset into a controller, you can also set the scenario with a parameter attribute:
use App\Rulesets\PostRuleset;
use CraftCms\RulesetValidation\Attributes\Scenario;
class PostController
{
public function storeDraft(#[Scenario(PostRuleset::SCENARIO_DRAFT)] PostRuleset $ruleset)
{
$validated = $ruleset->validate();
// ...
}
}When a ruleset is validating an Illuminate\Http\Request, the Laravel docs above apply directly to the following features:
rules()authorize()messages()attributes()prepareForValidation()withValidator()after()validated()safe()#[StopOnFirstFailure]#[RedirectTo]#[RedirectToRoute]#[ErrorBag]- Precognition support
This package mirrors that behavior, with a few small differences:
validate()returns the validated payload directly, like$request->validate(...).only(...)returns a scoped clone that validates only a subset of attributes, such as$ruleset->only('title')->validate().passes(),fails(), andgetValidator()are available when you want a non-throwing validation flow.- Request-backed rulesets may be injected directly into controller actions.
- For object-backed validation, data comes from
validationData()instead of request input. - Rulesets can be selected with either the
#[Ruleset(...)]attribute or aruleset(): stringmethod on the validatable object.
You can associate a validatable object with a ruleset in two ways.
use App\Rulesets\CreatePostRuleset;
use CraftCms\RulesetValidation\Attributes\Ruleset;
#[Ruleset(CreatePostRuleset::class)]
class CreatePostData implements ValidatesWithRuleset
{
// ...
}use App\Rulesets\AdminPostRuleset;
use App\Rulesets\CreatePostRuleset;
use CraftCms\RulesetValidation\Concerns\HasRuleset;
use CraftCms\RulesetValidation\Contracts\ValidatesWithRuleset;
class CreatePostData implements ValidatesWithRuleset
{
use HasRuleset;
public function __construct(
public bool $isAdmin,
public string $title,
) {}
public function validationData(): array
{
return [
'title' => $this->title,
];
}
public function ruleset(): string
{
return $this->isAdmin
? AdminPostRuleset::class
: CreatePostRuleset::class;
}
}composer testcomposer analysecomposer formatPlease see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.