【问题标题】:Laravel unique field validate not workingLaravel 唯一字段验证不起作用
【发布时间】:2016-08-08 17:06:22
【问题描述】:

我有一个名为 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;

【问题讨论】:

  • 应该是'mac' => '[required, unique:mac...]'
  • 验证中的字段在给定的数据库表上必须是唯一的。
  • 在此处添加您的表结构

标签: validation laravel


【解决方案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})$/',
];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-24
    • 2016-01-19
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    相关资源
    最近更新 更多