phplaravellaravel-validation

Laravel Validation on multiple string options


I have a string column in my table e.g status which contains 2 string values as constants, i am wanting to add the ability so users can update a status only on these 2 string values. The main purpose of the question is am wanting to add validation for the status in my controller which the user can only select online or offline as options

so basically the status column can be these 2 string values

  protected $validation = [
        'status' => 'string:online, offline
    ];

I know the above doesnt work but i need something similar to validate multiple constant values for the string column.

these are the constants for the status that i need to be using

public const ONLINE = 'online';
public const OFFLINE = 'offline';

is there a way you can add in validation for the visibility field using these constants? some help would be great.

full class file below:

protected $request;

protected $user;


protected $validation = [
    'name' => 'max:10'
];

protected $required = [
    'name'
];

public function __construct(Request $request = null)
{
    $this->request = $request;
}

Solution

  • You can use the constants to define the possible options:

    use Illuminate\Validation\Rule;
    
    $validation = [
            'status' => [Rule::in([Class::ONLINE,Class::OFFLINE])]
        ];
    

    Or better, define the constant STATUSES listing all the possible statuses in your class

    public const STATUS_ONLINE = 'online';
    public const STATUS_OFFLINE = 'offline';
    public const STATUSES = [self::ONLINE, self::OFFLINE];
    

    and use that constant

    use Illuminate\Validation\Rule;
    
    $validation = [
            'status' => [Rule::in(Class::STATUSES)]
        ];