Search code examples
phplaravellaravel-validation

How can I validate to check if a record having this value exists in a table?


I am working on a Laravel project and I have the following problem related to validation.

In the past I created this validation rules (related to a new user registration form):

$rules = [
    'name' => 'required',
    'surname' => 'required',
    'login' => 'required|unique:pm_user,login',
    'email' => 'required|email|confirmed|unique:pm_user,email',
    'pass' => 'required|required|min:6',
    'g-recaptcha-response' => 'required|captcha',
];

In particular this rules array contains this rule:

'login' => 'required|unique:pm_user,login',

it seems to me that this last rule check if the inserted login doesn't yet exist into the pm_user table (so it ensure that not exist a row of the pm_user table having the same inserted value into the login column).

Is it? Correct me if I am doing wrong assertion.

If it work in this way now my problem is how to do the opposite thing in another set of validation rule.

In particular I have this other array of rule (defined into a class extendingFormRequest:

public function rules() {
    return [
        'email' => 'required|email',
        'token' => 'required',
    ];
}

In particular I have to ensure that into the pm_user table yet exist a record having the value of the column named email that is the same of the emai field of the request.

How can I change this request to perform this validation rule?


Solution

  • Laravel 5.4 already has a built in validation rule for this called exists. https://laravel.com/docs/5.4/validation#rule-exists

    I think you are looking for:

    'email' => 'required|email|exists:pm_user,email'