Laravel独特的领域验证不起作用

时间:2016-08-08 08:45:00

标签: validation laravel

我有一个名为mac的字段,我存储mac地址,但我需要它是唯一的,以避免重复的mac地址。

代码:

return [
            'user_id' => 'required|integer',
            'mac' => array('required|unique:mac', 'regex:/^([0-9A-Z]{2}[-]){5}([0-9A-Z]{1,2})$/'),
        ];

错误: 方法[validateRequired | unique]不存在。

结构:

CREATE TABLE `devices` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(10) unsigned NOT NULL,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `mac` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `content` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT '0',
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `devices_mac_unique` (`mac`),
  KEY `devices_user_id_foreign` (`user_id`),
  CONSTRAINT `devices_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

1 个答案:

答案 0 :(得分:1)

您需要定义需要根据

检查mac地址的表
return [
    'user_id' => 'required|integer',
    'mac'     => 'required|unique:devices,mac|regex:/^([0-9A-Z]{2}[-]){5}([0-9A-Z]{1,2})$/',
];

更新 - 更新记录时,您可以将规则扩展到。

return [
    'user_id' => 'required|integer',
    'mac'     => 'required|unique:devices,mac,' . $device->id . '|regex:/^([0-9A-Z]{2}[-]){5}([0-9A-Z]{1,2})$/',
];