Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validation with enum column

I have this fields:

id, title, type

type is enum And I would like to validate my title by Type column, eg:

id | title | type
1 | test | option1
2| test | option2

So when someone tries to insert a row with this condition, validation should be processed for unique of the column.

3 | test | option1 ==> should not be insert due unique validation rule.

How will my validation rule look like?

Regards

// Edit 1: Rules facade was the solution.

like image 888
Payam Khaninejad Avatar asked Apr 10 '17 08:04

Payam Khaninejad


People also ask

How do you validate exact words in laravel?

To get the exact words to validate you can make use of Rule::in method available with laravel. Using Rule::in method whatever the values provided by this rule has to be matched otherwise it will fail.

What is the method used to configure validation rules in form request?

Laravel Form Request class comes with two default methods auth() and rules() . You can perform any authorization logic in auth() method whether the current user is allowed to request or not. And in rules() method you can write all your validation rule.


2 Answers

in:option1,option2 The field under validation must be included in the given list of values.

not_in:option1,option2 The field under validation must not be included in the given list of values.

You'r validation should look like the following, but it requires your to hard code your options in "in" parameters or 'implode' an array.

$validator = Validator::make(Input::only(['title', 'type']), [
    'type' => 'in:option1,option2, // option1 or option2 values
    'title' => 'required|min:6|max:255', //whatever rules you want ..
]);

You can avoid 'implode' by this way:

$validator = Validator::make(Input::only(['title', 'type']), [
        'type' => Rule::in(['option1', 'option2']), // option1 or option2 values
        'title' => 'required|min:6|max:255', //whatever rules you want ..
    ]);
like image 194
APu Avatar answered Sep 23 '22 19:09

APu


If the type field is not dynamic, you could use Rule class to add extra query in your validation rule.

return [
    'title' => [
        Rule::unique('tablename', 'title')->where(function ($query) {
            $query->where('type', 'option1');
        })
    ]
];

else, you can make custom validation rules.

like image 36
sazanrjb Avatar answered Sep 21 '22 19:09

sazanrjb