Skip to content

fix(laravel): validate the model instead of body #7165

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 22, 2025

Conversation

soyuka
Copy link
Member

@soyuka soyuka commented May 22, 2025

Q A
Branch? 4.1
Tickets fixes #6932
License MIT

With Eloquent, the model properties are in snake_case.
We've configured Symfony to convert camelCase to snake_case during normalization, so users send payloads like this:

{"surName": "foo"}

However, the serializer, if you send it:

{"sur_name": "foo"}

The serializer will correctly skip this property, but the HTTP Body has the field that appears to be correct.

But this causes problems with API Platform and Laravel. For instance, if we set a validation rule like this:

#[ApiResource(
    operations: [
        new Post(
            uriTemplate: '/issue_6932',
            rules: [
                'sur_name' => 'required'
            ]
        )
    ],
)]
class Issue6932 extends Model
{
}

The request will pass validation, but it won't pass serialization, and thus it will break during database insertion (for example, with non-nullable fields).
The issue with #6932 is that as Laravel validator works on arrays, we used the HTTP Body to validate. Except that the serialization phase of API Platform should already strip some unwanted attributes.

To resolve this we moved the ValidateProvider to work on the deserialized body. With eloquent models we can use $model->toArray() but for non-eloquent models we need to use the ObjectNormalizer again.

In this PR we also added a name conversion on validation property paths.

@soyuka soyuka force-pushed the camel-case-validation-colision branch from 46b11d0 to 79ccbd6 Compare May 22, 2025 07:57
@soyuka soyuka force-pushed the camel-case-validation-colision branch from 79ccbd6 to 2374ab2 Compare May 22, 2025 08:01
@soyuka soyuka force-pushed the camel-case-validation-colision branch from 2374ab2 to 45e3637 Compare May 22, 2025 08:06
@soyuka soyuka merged commit bf166bb into api-platform:4.1 May 22, 2025
94 of 96 checks passed
@soyuka soyuka deleted the camel-case-validation-colision branch May 22, 2025 08:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant