How to make Laravel Validator $ parameters optional?

Let's say I have a model Userwith two methods:

User.php

class User extends Eloquent
{  
    /* Validation rules */
    private static $rules = array(
        'user'  => 'unique:users|required|alpha_num',
        'email' => 'required|email'
    );

    /* Validate against registration form */
    public static function register($data)
    {
        $validator = Validator::make($data, static::$rules);
        if($validator->fails())
        {
            /*... do someting */
        }
        else
        {
            /* .. do something else */
        }
    }

    /* Validate against update form */
    public static function update($data)
    {
        $validator = Validator::make($data, static::$rules);
        if($validator->fails())
        {
            /*... do someting */
        }
        else
        {
            /* .. do something else */
        }
    }
}

My question is . How can I make validation rules optional, so even if the data for update()is just a field email, it ignores it Userand still checks for true.
Is this possible, or am I missing something?

Sorry for my bad english.

+2
source share
3 answers

Not sure if I am asking the question correctly, but if the user is optional, you should remove the 'required' from the validator. This way you will have:

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

instead:

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

, , .

:

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'
        );
    }
}

, , , , , .

, .

+8

Laravel update() , , , . update() .

"" :

  • "" $ .

    'user'  => 'unique:users|alpha_num',
    
  • update() .

+2

What about:

private static $rules = array(
    'user'  => 'unique:users|required|alpha_num',
    'email' => 'required|email'
);
private static $update_rules = array(
    'user'  => 'required|alpha_num',
    'email' => 'required|email'
);

* Validate against registration form */
public static function register($data)
{
    $validator = Validator::make($data, static::$rules);
    if($validator->fails())
    {
        /*... do someting */
    }
    else
    {
        /* .. do something else */
    }
}

/* Validate against update form */
public static function update($data)
{
    $validator = Validator::make($data, static::$update_rules);
    if($validator->fails())
    {
        /*... do someting */
    }
    else
    {
        /* .. do something else */
    }
}
0
source

Source: https://habr.com/ru/post/1540112/


All Articles