schwartzmj
1 month ago

Run validation on model already stored in database

Posted 1 month ago by schwartzmj

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. [email protected] 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.

Please sign in or create an account to participate in this conversation.