1

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?

1 Answer 1

2

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

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

2 Comments

Thanks - are there any other alternatives though? I'm thinking perhaps in a situation where I might want to have separate edit forms for a model that might have a large number of fields, instead of them all being on one page. Or is this considered poor practice?
In that case you might want to define multiple rule sets for each form and use them accordingly in your validate method. But if there are a lot of fields you should be able to group some of them into subsets and use them as separate entities.

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.