Home > Mobile >  Laravel 8 Validation rule not working for unique email error always returning false
Laravel 8 Validation rule not working for unique email error always returning false

Time:12-12

I need to insert customer data where the email will be unique. Here is the mysql

CREATE TABLE IF NOT EXISTS `customers` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customer_name` varchar(20) NOT NULL,
  `customer_address` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
  `customer_email` varchar(20) NOT NULL,
  `customer_city` varchar(50) NOT NULL,
  `post_code` varchar(20) NOT NULL,
  `customer_phone` int NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `customer_email` (`customer_email`)
) ENGINE=MyISAM AUTO_INCREMENT=16 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
COMMIT;

Here the customer model:

class Customer extends Model
{
    protected $table="customers";
    protected $fillable = ['customer_name', 'customer_email','customer_address', 'customer_city','customer_postcode'];
 }

And in the controller:

 $validator = Validator::make($request->all(),
            [
            'customer_name' => 'required',
            'customer_address' => 'required',
            'customer_email' => "required|unique:customers",
            'customer_city' => 'required',
            'post_code' => 'required',
            'customer_phone' => 'required',
        ]);

            var_dump($validator->fails());

The $validator->fails() always returns false. What i am missing? Thanks in advance.

CodePudding user response:

This is the proper unique validation method.

1: you have to add "unique" validation. 2: define table name like "registrations". 3: define column name like "primary_contact".

$validator = Validator::make($request->all(), [ 'primary_contact' => 'unique:registrations,primary_contact,null,null ]);

CodePudding user response:

See this solution I think you will find what you want. https://laracasts.com/discuss/channels/laravel/unique-email-not-working-on-validator

  • Related