Replies: 1 comment
-
function validate_nested_dto(
string $class,
string $nestedKey,
array $additionalRules = [],
bool $payload = false
): mixed {
abort_unless(is_subclass_of($class, Data::class), 500, 'Internal server error.');
abort_unless(method_exists($class, 'getValidationRules'), 500, 'Internal server error.');
$nestedKey = str_ends_with($nestedKey, '.') ? substr($nestedKey, 0, -1) : $nestedKey;
$rules = $payload ? $class::getValidationRules(request()) : $class::getValidationRules();
$rules = collect($rules)->mapWithKeys(fn(
$value,
$key
) => ["$nestedKey.$key" => $value])->toArray();
$rules[$nestedKey] = ['array', ...$additionalRules];
$validated = request()->validate($rules);
$dtoPayload = data_get($validated, $nestedKey);
if($dtoPayload === null) {
return null;
}
// abort_if($dtoPayload === null && !in_array('nullable', $additionalRules), 500, 'Internal server error.');
try {
return $class::validateAndCreate($dtoPayload);
} catch (ValidationException $e) {
throw ValidationException::withMessages(collect($e->errors())->mapWithKeys(static fn(
$value,
$key
) => [(str_starts_with($key, $nestedKey) ? $key : "$nestedKey.$key") => $value])->toArray());
}
} It's not pretty, but this is what I have at the moment. (I call |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi, I don't use DTOs much in my workflow except for the json columns in my tables. Since these json columns are part of the create/update requests (usually), I need to manually grab the validation rules for the data class and prepend the nesting to the array keys (e.g. if the data class represents the
question_data
column, I'd prependquestion_data.
to each of the generated validation rules, and use those manually in my request validator, followed by creating the data class instance manually usingfrom
orvalidationAndCreate
). This is important for providing validation errors at the correct nesting.If you overload
fromRequest
, you can change the mapping of the input data to the data class, but that doesn't seem to affect the generated validation rules.I could create a DTO that represents the request as a whole, but the problem with that approach is that sometimes the json data is polymorphic (multiple data classes could be used).
Perhaps adding a new annotation?
Beta Was this translation helpful? Give feedback.
All reactions