Skip to content

Error calling $request->validated() if no rules #322

@dfidler

Description

@dfidler

DESCRIPTION

If your action doesn't have any rules, ValidateActions doesn't set a validator (remains null) so if you call ActionRequest->validated() on this action, it throws a runtime error(can't call validated() on null) resulting in an error 500:

    # trait ValidateActions
    public function validated($key = null, $default = null): mixed
    {
        return data_get($this->validator->validated(), $key, $default);
    }

There are two really simple fixes;

OPTION 1 - return null; preferred

return data_get($this->validator?->validated(), $key, $default);

This will always return null (first stanza in data_get(...) )

OPTION 2 - return $default

return is_null($this->validator) ? $default : data_get($this->validator->validated(), $key, $default);

This was, initially, my preference because I can do something (in php 8.1+) like $request->validated(default: [ x => 1, y=> 2]) to avoid capturing nulls in the main code and responding with other values.

However, on further thought,, it's a bad idea because if you do ->validated('key', 'value'); then the purpose of $default changes based on whether you supply a $key or not... and that's bad.

Background

I found this because I have some code that does collect($request->validated()) in a base class action (I have several other actions that extend this one). It dead easy to work around this but it's still worthwhile to address it.

In fact, the first line of every asController method (and in the legacy controllers we haven't managed to eradicate yet) is always collect($request->validated())

Versions:

  • Laravel Actions: 2.7.3
  • Laravel: 9.52.20

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions