Skip to content

A suggestion to improve performValidation() function #207

@ghost

Description

Hello, me again here!

Below follows the performValidation() function from ValidatingTrait.

    /**
     * Validate the model against it's rules, returning whether
     * or not it passes and setting the error messages on the
     * model if required.
     *
     * @param  array $rules
     * @return bool
     * @throws \Watson\Validating\ValidationException
     */
    protected function performValidation($rules = [])
    {
        $validation = $this->makeValidator($rules);
        $result = $validation->passes();
        $this->setErrors($validation->messages());
        return $result;
    }

I'm just wondering if we can improve this function to validate against related models in addition to the base model. Do you think this can be a good idea?

My use case is just because i want to simplify some of my controllers. Today, they are handling validation from my services this way:

$profile = ProfileService::update($profile, $request->all());

// handle validation for all models
if ($profile->isInvalid() || $profile->address->isInvalid()) {
    return redirect()
        ->back()
        ->withInput()
        ->withErrors(array_merge_recursive(
            $profile->getErrors()->toArray(), 
            $profile->address->getErrors()->toArray()
        ));
}

As you see, my ProfileService::update() function save profile's data into both base and related model. Both models are using this trait. I wanna keep it simple and remove that mess after redirect().

Something like:

$profile = ProfileService::update($profile, $request->all());

// handle validation for all models at once
if ($profile->isInvalid()) {
    $profile->throwValidationException();
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions