简体   繁体   English

Laravel 自定义唯一验证规则

[英]Laravel custom unique validation with Rule

I've searched for some questions related to my problem here and have applied them.我在这里搜索了一些与我的问题相关的问题并应用了它们。 But the result still not what I wanted for.但结果仍然不是我想要的。 Here are the references:以下是参考资料:

Laravel conditional unique validation Laravel 条件唯一验证

Laravel | 拉拉维尔 | Unique validation where clause 唯一验证 where 子句

In my case, I want to validate the name field in the request to be unique when updating, only if the requested value is different from the previous stored name in the database.在我的情况,我想验证name字段中请求更新时,仅当请求的值从以前存储的不同是唯一的name在数据库中。 Here is my current code.这是我当前的代码。

if(Request::method() == 'PUT') $rules = array_merge($rules, [
        'name' => [
            'required',
            'string',
            'max:255',
            Rule::unique('tags')->where(function ($q) use ($request) {

                $q->where('name', '!=', strtolower($request['name']));
            })
        ]
    ]);

In my database, I have some rows of data.在我的数据库中,我有一些数据行。 The name s of those data are product, event, and campaign .这些数据的nameproduct、event 和 campaign When I want to update the campaign name with product in the request, the validation doesn't make this unique.当我想在请求中使用产品更新广告系列名称时,验证不会使其唯一。 It returns它返回

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'product' for key 'tags_name_unique' (SQL: update tags set name = product, tags . updated_at = 2020-10-08 02:35:52 where id = 14) SQLSTATE [23000]:完整性约束违规:1062重复项'产品'关键'tags_name_unique'(SQL:更新tags设置name =产品tagsupdated_at = 2020年10月8日二时35分52秒,其中id = 14)

I hope I explained it well.我希望我解释得很好。 Anyone can help me?任何人都可以帮助我吗? Thanks in advance.提前致谢。

Edit #1: My tags table migration:编辑 #1:我的tags表迁移:

public function up()
{
    Schema::create('tags', function (Blueprint $table) {
        $table->id();
        $table->string('name')->nullable()->unique();
        $table->text('description')->nullable();
        $table->timestamps();
    });
}

Edit #2:编辑#2:

Here is my request payload from Postman in JSON.这是我来自 Postman 的 JSON 请求负载。

{
    "id": 14,
    "name": "product",
    "description": "Descriptions"
}

I don't think you need to do all this just to check unique validation on the same model.我认为您不需要做所有这些只是为了检查同一模型上的唯一验证。

Have you tried this?你试过这个吗?

if(Request::method() == 'PUT') $rules = array_merge($rules, [
        'name' => [
            'required',
            'string',
            'max:255',
            'unique:tags',
])

This should work just fine.这应该工作得很好。 As mentioned in the docs here If you are checking all conditions for the same model then you don't to check the where condition explicitly.如此处的文档中所述如果您要检查同一模型的所有条件,则无需明确检查 where 条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM