Skip to content

Validation ​

FormRequest ​

The cleanest approach — validation runs before the controller method is even called:

php
// src/Slices/Flights/Http/CreateFlightRequest.php
use HexaGen\Core\Http\FormRequest;

class CreateFlightRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'origin'      => 'required|string|min:3|max:3',
            'destination' => 'required|string|min:3|max:3|different:origin',
            'price'       => 'required|numeric|min:0',
            'class'       => 'required|in:economy,business,first',
            'date'        => 'required|date|after:today',
            'email'       => 'required|email|unique:flights,email',
        ];
    }

    public function messages(): array
    {
        return [
            'origin.required'     => 'The origin airport code is required.',
            'destination.different' => 'Origin and destination must be different.',
        ];
    }

    public function attributes(): array
    {
        return [
            'origin'      => 'origin airport',
            'destination' => 'destination airport',
        ];
    }
}
php
// In controller — inject the FormRequest, validation is automatic
public function store(CreateFlightRequest $request): Response
{
    $flight = Flight::create($request->validated());
    return $this->json($flight->toArray(), 201);
}

If validation fails, a 422 Unprocessable Entity JSON response is returned automatically.

Available rules ​

RuleDescription
requiredField must be present and non-empty
nullableField may be null
sometimesOnly validate if present
stringMust be a string
numericMust be numeric
integerMust be an integer
booleanMust be true/false/1/0
arrayMust be an array
emailValid email address
urlValid URL
ip / ipv4 / ipv6Valid IP address
uuidValid UUID v4
jsonValid JSON string
dateValid date
acceptedMust be yes/on/1/true
min:nMin length/value
max:nMax length/value
between:min,maxBetween min and max
size:nExact length/value
digits:nExactly N digits
digits_between:min,maxBetween N and M digits
in:a,b,cMust be one of the values
not_in:a,bMust not be one of the values
same:fieldMust match another field
different:fieldMust differ from another field
confirmedMust match field_confirmation
starts_with:a,bMust start with one of the values
ends_with:a,bMust end with one of the values
after:dateDate must be after
before:dateDate must be before
required_if:field,valueRequired when another field equals value
unique:table,colMust be unique in DB
unique:table,col,ignoreIdUnique except for this ID (for updates)
exists:table,colMust exist in DB

Released under the MIT License.