schwartzmj's avatar

Run validation on model already stored in database

I'm looking for a way to run validation rules on models already stored in my database. When searching for this, every resource that I find has to do with validating incoming form requests.

I've tried this inside of the model:

    protected $rules = [
        'name' => 'required',
        'address' => 'required',
        'city' => 'required',
        'zip' => 'required',
        'phone' => 'required',
        'email' => 'required|email',
        'authorize_release_information' => 'required'
    ];

    private $errors;

    public function validate()
    {
        $validator = Validator::make($this->attributes, $this->rules);
        if ($validator->fails()) {
            $this->errors = $validator->errors();
            return false;
        }
        return true;
    }

    public function errors()
    {
        return $this->errors->all();
    }

which seems to work, kind of. It seems to work for fields that are "required", and gives back the correct errors, but it considers an obviously incorrect email as valid (e.g. person@example is considered a valid email).

My use case is that I have a form that is automatically created and I want the user to update it, but I'd like to be able to tell them if there are currently errors or not from the automatically created form.

0 likes
5 replies
automica's avatar

@schwartzmj create a new request object using your existing data and then you can use your validation rules.

 $request = new Request([
    'email' => '[email protected]'
]);

$result = $this->validate($request, [
    'email' => 'required|email',
]);
schwartzmj's avatar

Thanks for the help. This seems a bit hacky or unintended. Is this a normal way of going about this? I'm surprised there's no "built in" way of doing it.

schwartzmj's avatar

Turns out my issue was that 'required|email' needed to be 'required|email:filter'

Apparently "foo@bar" is considered a valid email address if you don't tag on ':filter'.

Please or to participate in this conversation.