Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

NoLAstNamE's avatar

validate enums in PHP 8.0

I know that we can validate enums as seen in the documentation, but this is only available on PHP 8.1+ and I used PHP 8.0, for now, I won't use that.

I have the example below from this answer by @martinbean

class Post extends Model
{
    const STATUS_DRAFT = 1;
    const STATUS_PUBLISHED = 2;

    public function scopeDrafts($query)
    {
        return $query->whereStatus(static::STATUS_DRAFT);
    }

    public function scopePublished($query)
    {
        return $query->whereStatus(static::STATUS_PUBLISHED);
    }
}

How to validate those constants declared in Post model in a request? Something like the example below.

public function rules()
{
    return [
         'gender' => 'required|in:Male,Female',
    ];
}
0 likes
3 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

I assume you mean this

public function rules()
{
    return [
         'gender' => [
                 'required',
                 Rule::in([Post::STATUS_DRAFT, Post::STATUS_PUBLISHED]),
    ], 
    ];
}

 
3 likes
martinbean's avatar

@benjamin1509 TIL. That enum validation looks nice! Definitely need to upgrade some PHP applications from 8.0 and 8.1.

2 likes

Please or to participate in this conversation.