How to make Laravel's Validator $rules optional?

前端 未结 3 1926
南笙
南笙 2021-01-15 04:47

Let\'s say I have User model with two methods:

User.php

class User extends Eloquent
{  
    /* Validation rules */
             


        
3条回答
  •  误落风尘
    2021-01-15 05:26

    Not sure if I'm getting your question right but if the user is optional you should remove 'required' from the validator. This way you will have:

    'user'  => 'unique:users|alpha_num',
    

    instead of:

    'user'  => 'unique:users|required|alpha_num',
    

    On the other hand I create a custom method for my models that is able to return custom validation rules depending on incoming parameters.

    For example:

    private function getValidationRules($rules)
    {
        if ($rules == UPDATE_EMAIL)
        {
            return array('email' => 'required|email');
        } else {
            return array(
                'user'  => 'unique:users|required|alpha_num',
                'email' => 'required|email'
            );
        }
    }
    

    I guess it's only a personal choice, but I have found that getting the validation rules from a method allows more control over what I really want to validate, especially when you want to perform some advanced validations.

    Hope it helps you.

提交回复
热议问题