Check if field exists in Input during validation using Laravel

isset, laravel, laravel-4, validation

Solution

You should make custom validator like this.

use Symfony\Component\Translation\TranslatorInterface;

class CustomValidator extends Illuminate\Validation\Validator {

    public function __construct(TranslatorInterface $translator, $data, $rules, $messages = array())
    {
        parent::__construct($translator, $data, $rules, $messages);

        $this->implicitRules[] = 'AttributeExists';
    }

    public function validateAttributeExists($attribute, $value, $parameters)
    {
        return isset($this->data[$attribute]);
    }
}

This will make AttributeExists work without to use require. For more explain about this. When you want to create new validator rule. If you don't set it in $implicitRules, that method will not work out if you don't use require rule before it. You can find more info in laravel source code.

Problem

I want to make sure that certain fields are posted as part of the form but I don;t mind if some are empty values. The 'required' validation rule won't work as I am happy to accept empty strings. I have tried the below, but as the 'address2' field is never sent, the validator doesn't process it. Any ideas? ``` $rules = array( 'address2' => 'attribute_exists' ); class CustomValidator extends Illuminate\Validation\Validator { public function validateAttributeExists($attribute, $value, $parameters) { return isset($this->data[$attribute]); } } ```

Original source