Validating a request with admin model rules
Model::validator() builds Laravel validation rules from the fields of the admin model and returns the data mutated the same way as the admin form does it (checkboxes become 0/1, empty strings null, files are uploaded, locale values are cleaned).
The rules come from the field definitions, see validation rules.
app/Http/Controllers/CustomerController.php
validate() throws a validation exception. A JSON request receives the standard 422 response with errors, other requests are redirected back with errors in session.
The current request is used by default, pass another one with Customer::validator($request). The same method exists on a model instance, $customer->validator().
Supported methods
only
Validates and returns only given fields. A key with rules also merges the rules.
merge
Adds rules. A new key adds a field which is not in the model (it is also returned by getData()), an existing key appends rules to the model rules.
replace
Replaces the model rules of given fields.
validate
Validates the request and returns the validator for chaining.
getData
Returns validated keys only, mutated by the admin request mutators.
get
Returns one mutated value, with an optional default.
fill
Fills the model with validated data, additional attributes can be passed.
use
Applies an Admin Request class.
Validating with validateRequest()
validateRequest() is a shorter form which validates the current request with the field rules and returns the data mutated the same way as the admin form does.
app/Http/Controllers/ContactController.php
Mutated values are merged back into
request(). A JSON request receives 422 with errors, other requests are redirected back with errors in session. Translatable fields listed in $fields are validated in every language.
The rules of a model are available as an array:
required get nullable, locale fields are validated as name.en (required only in the default language), multiple files as photos.*, and a required file field is optional when the record already has a file.
Fields are resolved for the given row only when the model reads it in fields($row), or when one of its modules does, such as the unique rule of a slug column. Override hasRowDependentFields() and return true in a model building its fields per record in another way.
One validator instance builds its rules and mutated data once. A change through only(), merge() or replace() builds them again, so the request mutators, including file uploads, run once per state.