Skip to content
This repository was archived by the owner on Jul 16, 2023. It is now read-only.
This repository was archived by the owner on Jul 16, 2023. It is now read-only.

Uniqueness #37

Closed
Closed
@ghost

Description

Since validation rules are declared as static, it is not possible to use instance variables to validate models for uniqueness?

When updating a user for example, you want to ignore uniqueness for the user being updated. You can do this by specifying the ID of the model to ignore. Otherwise the validation rules will fail as the user you are updating has the same email address as the user you are updating.

'email' => 'unique:users,email_address,10'

By using a Validator service you can pass an instance of the model into a method and return a validator object for that model which you can check on save.

namespace Models\Services\Validators;

use Models\User;
use Validator;

class UserValidator {

    public static function getValidator(User $user) {
        $rules = [
            'first_name'  => 'required|max:50',
            'last_name'   => 'required|max:50',
            'email'       => "required|max:100|email|unique:users,email{$user->id}"
        ];

        return Validator::make($user->toArray(), $rules);
    }

}

You can't do this with a static variable on a model.

// This will fail if you are updating an existing user.
public static $rules = array(
    'email' => 'required|email|unique,users,email',
);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions