0

I have the following Enum in Laravel:

final class LeadState extends Enum
{

    const OPEN = 1;

    const NOT_REACHED = 2;

    const RECALL = 3;

    const NO_INTEREST = 4;

    const APPOINTMENT = 5;

    const BLACKLIST = 6;

    const CLOSED = 7;

    const INVALID = 8;

    const TOO_MANY_TRIES = 9;

    const APPOINTMENT_NEEDED = 10;

    const COMPETITION_PROTECTION = 11;
}

I am using this class in a Rule.

 public function rules()
    {
        return [
            'reason' => 'sometimes|nullable|string',
            'isDeleteAppointment' => 'sometimes|nullable|boolean',
            'leadId' => 'sometimes|nullable|numeric',
            'comment.lead_id' => 'sometimes|numeric',
            'comment.date' => 'sometimes|nullable',
            'comment.body' => 'sometimes|nullable|string',
            'comment.reason' => [
                'sometimes',
                'nullable',
                'string',
                Rule::in(LeadState::asArray()) // Calling the enum here.
            ]
        ];
    }

But, I need the enum names as array not the values. How can I do this? Above where I am calling the enum as an array. But, I am getting values like [1,2,3...]. But I need ['OPEN', 'NOT_REACHED'...] like this.

Abhijit Mondal Abhi
  • 1,364
  • 4
  • 15
  • 34
  • 1
    https://stackoverflow.com/questions/956401/can-i-get-consts-defined-on-a-php-class – V-K Feb 10 '21 at 09:41

1 Answers1

2

You could do something like this:

<?php
final class LeadState extends Enum
{
    const OPEN = 1;
    const NOT_REACHED = 2;
    const RECALL = 3;
    const NO_INTEREST = 4;
    const APPOINTMENT = 5;
    const BLACKLIST = 6;
    const CLOSED = 7;
    const INVALID = 8;
    const TOO_MANY_TRIES = 9;
    const APPOINTMENT_NEEDED = 10;
    const COMPETITION_PROTECTION = 11;

    static function getConstants() {
        $oClass = new ReflectionClass(__CLASS__);
        return $oClass->getConstants();
    }
}

Then do this:

public function rules()
{
    return [
        'reason' => 'sometimes|nullable|string',
        'isDeleteAppointment' => 'sometimes|nullable|boolean',
        'leadId' => 'sometimes|nullable|numeric',
        'comment.lead_id' => 'sometimes|numeric',
        'comment.date' => 'sometimes|nullable',
        'comment.body' => 'sometimes|nullable|string',
        'comment.reason' => [
            'sometimes',
            'nullable',
            'string',
            Rule::in(array_keys(LeadState::getConstants()))
        ]
    ];
}

Source: https://www.php.net/manual/en/reflectionclass.getconstants.php#115385