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.

Ludger
  • 991
  • 2
  • 11
  • 22

2 Answers2

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();
Mark Bertenshaw
  • 5,594
  • 2
  • 27
  • 40
vvanasten
  • 941
  • 8
  • 14
  • 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 http://stackoverflow.com/questions/693691/php-how-to-initialize-static-variables – Ludger Apr 21 '14 at 22:58
  • Wow. I totally missed the fact that they were static even though I copied the code. – vvanasten Apr 21 '14 at 23:01
  • @wansten I updated your answer so that it can be used with static variables. – Ludger Apr 21 '14 at 23:04
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
}
afarazit
  • 4,907
  • 2
  • 27
  • 51