Use Laravel validations when html input names vary from column name

I cannot get passed required validation in my Laravel app.

This is the validation rule I have...

$rules = [
   'email' => 'required|unique:members|max:100',
];

The specific column name is email. The HTML page input field name is emailAddress

What to do in these situations ? How to tell this validation which request field to check ?

Thanks!

3 answers

  • answered 2018-01-11 20:25 N Mahurin

    You don't check against column names in validation, just use the input name.

    $rules = [
       'emailAddress' => 'required|unique:members|max:100',
    ];
    

    I guess to be more clear: the Request instance is what is checked. Validation doesn't interact with the database, it interacts with the Request

  • answered 2018-01-11 20:25 Alexey Mezenin

    You can change the name attribute to email.

    Or you can use validation rules like this:

    'emailAddress' => 'required|unique:members|max:100',
    

    And then in controller method do this:

    Model::create([
        'email' => $request->emailAddress,
    ]);
    

  • answered 2018-01-11 20:58 TharinduLucky

    Found the problem...

    It's the input field names that validation checks. Not column names.

    The problem here is the unique validation rule of the email field. I had to speficify which column to check for already stored emails.

    Like this

    unique:members,email
    

    I had to use the column name after the table name separated by a , (comma).

    So, the rule will be like

    $rules = [
        'emailAddress' => 'required|unique:members,email|max:100',
    ];
    

    That's it!