【问题标题】:making the combination of 2 fields unique and validate them in laravel使 2 个字段的组合唯一并在 laravel 中验证它们
【发布时间】:2023-04-07 13:13:01
【问题描述】:

我有一个名为contacts 的表,其中包含contact_iduser_id。 我想让这两个字段的组合独一无二并验证它们。所以我在迁移中所做的是:

$table->integer('user_id');
$table->integer('contact_id');
$table->timestamps();
$table->unique(['user_id', 'contact_id']);

这使得组合独一无二,当我尝试使用此代码插入重复项时:

Contact::create([
    'contact_id' => $request->input('contact_id'),
    'user_id' => $request->input('user_id'),
]);
return redirect(route('person-search'));

我收到此错误:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1-2' for key 'contacts.contacts_user_id_contact_id_unique' (SQL: insert into `contacts` (`contact_id`, `user_id`, `updated_at`, `created_at`) values (2, 1, 2020-12-05 09:26:09, 2020-12-05 09:26:09))

我想验证这 2 列并向我的用户显示自定义错误,而不是这个错误。我该如何为此编写验证?

【问题讨论】:

  • 你能包含你当前正在插入的 PHP 代码吗?
  • 添加到问题中
  • 为什么有一个名为contacts 的数据透视表?这不是好的做法,并且违反了 Laravel 的命名约定。它应该被称为contact_user

标签: php laravel validation


【解决方案1】:

As explained in the documentation,您可以轻松编写自定义验证规则。回调函数接收字段的名称和值,以及可用于发出错误消息的回调。

所以,只需编写一些东西来对这两个值进行数据库查询。作为一个快速而肮脏的例子,我永远不会投入生产:

$validator = Validator::make($request->all(), [
    'contact_id' => [
        function($k, $v, $f) {
            $result = DB::table('contacts')
                ->select('*')
                ->where('contact_id', $v)
                ->where('user_id', request()->user_id)
                ->first();
            if ($result) {
                $f("Duplicate value");
            }
        }
    ],
    ...
]);

另一种选择是将创建包装在 try/catch 中,如果创建因该错误而失败,则抛出 ValidationException

【讨论】:

    猜你喜欢
    • 2019-07-12
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    • 2019-03-24
    • 2011-05-01
    • 1970-01-01
    • 2023-03-20
    • 2020-08-02
    相关资源
    最近更新 更多