1

I'm trying to make an enum column validation in laravel. This is the code of my validator.

/**
 * Returns the rules and messages for validating this creation
 */
public static function ValidationBook($except = [], $append = []) {
    $book = ['rules' => [], 'messages' => []];
    $arr = config('constants.publication_statuses');
    $arrKeys = array_keys($arr);
    $book['rules'] = [
        'concert.title' => 'required|string',
        'concert.user_id' => 'required|exists:users,id',
        'concert.type' => [
            'required',
            Rule::in(['public', 'private']),
        ],
        'concert.status' => 'required',
        'concert.closes_on' => 'nullable'
    ];
    $book['messages'] = [

        'concert.title.required' => 'El título es requerido.',
        'concert.title.string' => 'El título debe ser un texto',

        'concert.user_id.exists' => 'Se debe ingresar un usuario válido.',

        'concert.type.required' => 'El tipo es requerido.',

        'concert.status.required' => 'El status es requerido.',
    ];
    if (!empty($except)) {
        $except = array_flip($except);
        $book['rules'] = array_diff_key($book['rules'], $except);
    }
    if (!empty($append)) {
        $book = array_merge_recursive($book, $append);
    }
    return $book;
}

The enum column is the type column. Also I've tried to do 'concert.type' => 'required|in:public,private'

Then I create my Validator using the following code:

$vb = Concert::ValidationBook($except, $append);
$validator = Validator::make($data, $vb['rules'], $vb['messages']);

But for some reason, when I send the post via Postman, i got "detail": "Undefined index: concert.type". Even when my data is:

{
    "concert": {
        "title": "Title",
        "type": "novalidtype",
        "status": "open"
    }
}

Thanks in advance

Jacobo
  • 1,259
  • 2
  • 19
  • 43
  • Does this answer your question? [Laravel IN Validation or Validation by ENUM Values](https://stackoverflow.com/questions/28976658/laravel-in-validation-or-validation-by-enum-values) – steven7mwesigwa Mar 24 '21 at 08:59

1 Answers1

5

Normally enum will be set in database like, and front end will be a drop down list

$table->enum('concert_type', ['public', 'private']);

However you can try out this solution

'concert_type' => 'in:public,private', // Public or Private values

Lim Kean Phang
  • 501
  • 4
  • 6