Ludger
Ludger

Reputation: 1031

php static array variables

I currently have the following code:

public static $validate = array(
    'first_name'=>'required',
    'last_name'=>'required',
    'email'=>'required|email'
);

public static $validateCreate = array(
    'first_name'=>'required',
    'last_name'=>'required',
    'email'=>'required|email',
    'password'=>'required|min:6'
);

I would like to know if its possible to reference the first static validate array and just add the extra one validation rule without rewriting the whole rule as I am currently doing.

I know you can not reference any variables from static declarations but I would just like to know if there are any better ways of storing model validation rules in a model.

Upvotes: 0

Views: 10753

Answers (2)

vvanasten
vvanasten

Reputation: 951

You can use array_merge to combine $validate and just the unique key/value of $validateCreate. Also, since you are using static variables you can do it like the following with all of the code in your model PHP file:

 class User extends Eloquent {

    public static $validate = array(
        'first_name'=>'required',
        'last_name'=>'required',
        'email'=>'required|email'
        );
    public static $validateCreate = array(
        'password'=>'required|min:6'
        );

    public static function initValidation()
    {
        User::$validateCreate = array_merge(User::$validate,User::$validateCreate);
    }
}
User::initValidation();

Upvotes: 4

afarazit
afarazit

Reputation: 4984

You can add the extra field in your static array directly when needed, for example

function validate()
{
    if($userIsToBeCreated)
    {
        static::$validate['password'] = 'password'=>'required|min:6';
    }
    // stuff here
}

Upvotes: 0

Related Questions