Iain
Iain

Reputation: 1734

Laravel validate model

I've created an Employer model in my Laravel 4 application and, in Employer.php I have created the following function to validate user input before saving it to the database:

public static function validate($input)
{
    $validator = Validator::make($input, static::$rules);

    if ($validator->fails() {
        return $validator;
    }

    return true;
}

This works fine when I'm creating a new record in the database, because I am passing in values for all the rules where I have specified a particular field is required.

However, there are certain fields in the database I don't want the user to edit after they have been created (for example, business_name). On the controller's edit method I create a form and omit those fields from the form. But validation fails because business_name is required by the $rules.

As a temporary work around, I tried just creating a hidden field in the edit form and populating it with the business_name. However, this is also required to be unique and fails when I PATCH my form to the update method!

Any advice? Is there any way I can specify which validation rules should be applied depending on the method calling it? Or should I create a new method in Employer.php specifically to validate on the update method?

Upvotes: 1

Views: 2218

Answers (1)

Bogdan
Bogdan

Reputation: 44526

You could use the required_without validation rule. Since an newly instantiated model doesn't have an id field yet, you can require some fields only when id is not present. This should work:

public static $rules = array(
    'business_name' => 'required_without:id'
);

http://laravel.com/docs/validation#rule-required-without

Upvotes: 2

Related Questions