Skip to content
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

Form request validated data is not casted to enum #87

Open
nicolasbeauvais opened this issue Dec 2, 2021 · 3 comments
Open

Form request validated data is not casted to enum #87

nicolasbeauvais opened this issue Dec 2, 2021 · 3 comments
Labels
enhancement New feature or request question Further information is requested

Comments

@nicolasbeauvais
Copy link
Contributor

nicolasbeauvais commented Dec 2, 2021

Hello 👋,

When casting enums in a Form Request, only the data payload in the Request instance is getting cast. So if following best practice and getting the data with the validated method in a controller, the original pre-cast data will be returned.

class Controller
{
    public function index(MyFormRequest $request)
    {  
        $request->validated()); // Doesn't return cast data

        $request->get('status'); // Return cast data
    }
}

As a fix, I created an enhanced TransformsEnums trait implementing the following method:

public function withValidator(Validator $validator)
{
    $validator->after(function (Validator $validator) {
        $data = $validator->getData();

        /** @var Enum $enumClass */
        foreach ($this->enums() as $key => $enumClass) {
            Arr::set($data, $key, $enumClass::from($this[$key]));
        }

        $validator->setData($data);
    });
}

Do you think that this is something that could be added to the package?

I could draft a PR on this, but given the native enum support on PHP 8.1 I wanted to make sure you would continue the maintenance of laravel-enum before working on it.

Cheers.

@github-actions
Copy link

This issue is stale because it has been open 21 days with no activity. Remove stale label or comment or this will be closed in 7 days

@nicolasbeauvais
Copy link
Contributor Author

Not stale

@Gummibeer Gummibeer removed the stale label Feb 5, 2022
@Gummibeer Gummibeer reopened this Feb 5, 2022
@Gummibeer Gummibeer added enhancement New feature or request question Further information is requested labels Feb 5, 2022
@Jasperscheper
Copy link

Any updates on this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request question Further information is requested
Projects
None yet
Development

No branches or pull requests

3 participants