0

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.

2 Answers 2

4

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();
Sign up to request clarification or add additional context in comments.

3 Comments

You cant use array merge as a static variable when initializing it, so what i did is added a piece of code after my model definition just to update the create validation array with the validation rule stackoverflow.com/questions/693691/…
Wow. I totally missed the fact that they were static even though I copied the code.
@wansten I updated your answer so that it can be used with static variables.
0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.