0

I have a question about Laravel 4 and Validation concept.

I have my mysql table and my model Calass.. We can suppose that we have a field nullable...

If this field is not null how can I validate it? (for example I would an integer value < of my maxvalue)

2
  • i think you can not have this feature. i can not find in laravel documents Commented Feb 17, 2014 at 12:22
  • All fields are nullable by default, unless you make them not null. You'd just validate them as you would anything else. You should also note the Validator class does not care about the columns in your database, all it's doing is validating data. Commented Feb 17, 2014 at 12:59

2 Answers 2

1

Unless you add the 'required' rule, validation will always treat fields as optional. Thus, a rule like numeric|max:9000 will be valid if the field is null or empty string, but if it is provided it has to be a number that is smaller than 9000.

To prevent null or empty string from being saved into the database (MySQL will convert this to 0 for an integer field), you can set up a mutator for the attribute. In your model:

public function setNumberAttribute($value)
{
    if ($value !== null && is_numeric($value)) {
        $this->attributes['number'] = (int) $value;
    }
}

http://laravel.com/docs/eloquent#accessors-and-mutators

Sign up to request clarification or add additional context in comments.

Comments

0

you can create your validation into your model

Ex:

class User extends Eloquent {

        protected $table = 'users';

        public $timestamps = false;

        public static function validate($input) {
                $rules = array(
                        # place-holder for validation rules
                );

                # validation code
        }

}

for more description about validation laravel book

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.