required_if validation rule with array values.

Posted 8 months ago by ravasaurio

I have a form for my admin to create new users. This is where the data is validated:

public function rules()
    {
      return [
            'first_name'     => 'required|max:191',
            'last_name'  => 'required|max:191',
            'email'    => ['required', 'email', 'max:191', Rule::unique('users')],
            'timezone' => 'required|max:191',
            'password' => 'required|min:6|confirmed',
            'roles' => 'required|array',
        ];
    }

In my form, there are some switches you may turn on/off to select the roles you want to assign the new user. roleswill be an array containing the role names you have selected. This is how the array looks like on the logs with more than one role selected:

array ( 

0 => 'administrator',
1 => 'executive',
2 => 'user',
)

What I need is to have some extra fields required, only if the user role was selected:

public function rules()
    {
      return [
            'first_name'     => 'required|max:191',
            'last_name'  => 'required|max:191',
            'email'    => ['required', 'email', 'max:191', Rule::unique('users')],
            'timezone' => 'required|max:191',
            'password' => 'required|min:6|confirmed',
            'roles' => 'required|array',
        'extra_field_1' => 'required_if:',//<--'user' role was selected? then this field will be required
        ];
    }

I have tried something like this:

'extra_field_1' => 'nullable|required_if:roles,User',

'extra_field_1' => 'required_if:roles,==,User',

'extra_field_1' => 'nullable|required_if:roles,user',

'extra_field_1' => 'required_if:roles,==,user',

Testing those, I selected the 'user' role and then left the extra fields empty to see if the validation fails and it doesn`t. Instead I get an SQLexception from trying to insert null data on not null columns (When I send the form, if the users role was selected the value of those extra fields will be inserted on a table which is different from the users table). If I am not mixing concepts, if validation fails the function that stores the user and gets me the SQLexception should not be executed right?

How can I get that required_if working? Thanks.

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.