Home > Software engineering >  Laravel 9 How to Validate Optional Enum Values
Laravel 9 How to Validate Optional Enum Values

Time:09-15

I'm using the new enum class in my Laravel application and want to validate optional parameters. I'm able to validate enum parameters if I pass them, but if I don't pass anything, I get the error, "Undefined array key".

My enum class is:

enum SortBy: string {
    case DateEntered = 'date_entered';
}

And my validation is:

$validatedData = $request->validate([
    'sortBy' => [new Enum(SortBy::class)]
];

This works if I make a request with my "sortBy" parameter equal to "dated_entered". If I omit "sortBy" though, I get the "undefined" error.

I tried this as well, but no luck:

$validatedData = $request->validate([
    'sortBy' => [new Enum(SortBy::class), 'nullable']
];

Other things I've tried:

$validatedData = $request->validate([
    'sortBy' => ['exclude_if:sortBy,null', new Enum(SortBy::class)]
];
$validatedData = $request->validate([
    'sortBy' => ['nullable', new Enum(SortBy::class)]
];
$validatedData = $request->validate([
    'sortBy' => ['sometimes', new Enum(SortBy::class)]
];

CodePudding user response:

I figured it out. It was an error in my code elsewhere =/

Enums are so new to me that I was tunnel-visioning.

This worked fine:

$validatedData = $request->validate([
    'sortBy' => [new Enum(SortBy::class)]
];

What the issue ended up being was that I needed to check that "sortBy" was set in my $validatedData variable.

So from this:

$validatedData['sortBy']
    ? SortBy::from($validatedData['sortBy'])
    : null,

To this:

isset($validatedData['sortBy'])
    ? SortBy::from($validatedData['sortBy'])
    : null,
  • Related