php Laravel 在更新中检查没有自身的唯一规则

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28198897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:43:58  来源:igfitidea点击:

Laravel check for unique rule without itself in update

phplaraveluniquerulelaravel-validation

提问by user3714582

I am having my validation rules for unique in the update section.

我在更新部分有我的唯一验证规则。

In inserting or adding the unique rule is 'Email' => array('unique:driver_details'),and it will check for the unique coloumn.

在插入或添加唯一规则时'Email' => array('unique:driver_details'),,它将检查唯一列。

But this fails for the update section. While updating it satisfies the other rules and in the unique of email it is checking itself for the unique coloumn and it fails but seeing its own field.

但这对于更新部分失败了。虽然更新它满足其他规则,并且在电子邮件的唯一性中,它正在检查自己是否有唯一的列,但它失败了,但看到了自己的字段。

So, how can i check for the unique except its own value in the database ?

那么,我如何检查数据库中除了它自己的值之外的唯一值?

回答by user3714582

This forces to ignore specific id:

这会强制忽略特定的 id:

'email' => 'unique:table,email_column_to_check,id_to_ignore'

replace segments table, email_column_to_check, id_to_ignorein above example

替换段table, email_column_to_check,id_to_ignore在上面的例子中

You could check it here http://laravel.com/docs/4.2/validation#rule-unique

你可以在这里查看http://laravel.com/docs/4.2/validation#rule-unique

回答by Arian Acosta

For those using Laravel 5 and Form Requests, you may get the id of the model of the Route-Model Binding directly as a property of the Form Request as $this->name_of_the_model->idand then use it to ignore it from the unique rule.

对于那些使用 Laravel 5 和表单请求的人,您可以直接获取路由模型绑定模型的 id 作为表单请求的属性,$this->name_of_the_model->id然后使用它从唯一规则中忽略它。

For instance, if you wanted to have unique emails, but also allow an administrator to edit users, you could do:

例如,如果您想要拥有唯一的电子邮件,但也允许管理员编辑用户,您可以执行以下操作:

Route:

路线:

Route::patch('users/{user}', 'UserController@update');

Controller:

控制器:

public function update(UserRequest $request, User $user) 
{
    // ...
}

Form Request:

表格请求:

class UserRequest extends FormRequest
{
    // ...
    public function rules()
    {
        return [
            'name' => 'required|string',
            'email' => [
                'required',
                'email',
                Rule::unique('users')->ignore($this->user->id, 'id')
            ],
            //...
        ];
    }
    //...
}

Please note that we are ignoring the user that is being edited, which in this case could be different than the authenticated user.

请注意,我们将忽略正在编辑的用户,在这种情况下,该用户可能与经过身份验证的用户不同。

回答by Ronish

$request->validate([
    'email' => 'unique:table_name,email,' . $user->id
]);

回答by Neeraj Shrestha

Include Rule by writing

通过书写包含规则

use Illuminate\Validation\Rule;

and write your validation code as follows:

并编写您的验证代码如下:

 'Email' => [required,
            Rule::unique('driver_details')->ignore($id),
            ]

Here $id is the id of the email that you want to ignore during validation which is obtained from the controller.

这里 $id 是您在验证期间要忽略的电子邮件的 ID,它是从控制器获取的。

回答by yesnik

In Laravel 6 app it helped me to exclude current user's email from validation:

在 Laravel 6 应用程序中,它帮助我从验证中排除了当前用户的电子邮件:

use Illuminate\Validation\Rule;

public function update(Request $request, $id)
{
    $request->validate([
        'email' => [
            'email',
            'required',
             Rule::unique('claims')->ignore($id),
        ],
    ]);

    // ...
}

回答by mwafi

Try this

尝试这个

'email' => 'unique:table_name,column_name,'.$this->id.',id'

$this->idwill be the value from your request

$this->id将是您请求的价值

回答by Nirav Bhoi

I am using Laravel 5.2

我正在使用 Laravel 5.2

if your primary key is named 'id' table name is users_table and I want to update user_name so I do it this way

如果您的主键名为 'id' 表名是 users_table 并且我想更新 user_name 所以我这样做

'user_name'  =>  'required|unique:users_table,user_name,'.$id

if your primary key is not named 'id' In my case my primary key is user_id and table name is users_table and I want to update user_name

如果您的主键未命名为 'id' 在我的情况下,我的主键是 user_id,表名是 users_table,我想更新 user_name

so I do it this way

所以我这样做

'user_name' => 'required|unique:users_table,user_name,'.$id.',user_id'

回答by Juha Vehnia

This took me a while to figure out but when you are dealing with update/create requests you also have access to the request object. Here I am enforcing that client names are unique but allowing currently edited client.

这花了我一段时间才弄清楚,但是当您处理更新/创建请求时,您还可以访问请求对象。在这里,我强制客户端名称是唯一的,但允许当前编辑的客户端。

class CreateUpdateClientRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => [
                'required',
                'string',
                'min:3',
                'max:50',
                Rule::unique('clients')->ignore($this->request->get('id'))
            ],
            'primary_contact_name' => 'required|string|min:3|max:50',
            'primary_contact_email' => 'required|string|email|min:5|max:50',
            'primary_contact_phone' => 'nullable|string|min:5|max:50',
            'secondary_contact_name' => 'nullable|string|min:3|max:50',
            'secondary_contact_email' => 'nullable|string|email|min:5|max:50',
            'secondary_contact_phone' => 'nullable|string|min:5|max:50',
            'notes' => 'nullable'
        ];
    }
}

回答by fabian

Been facing this issue for a while also. Try this:

也遇到这个问题有一段时间了。尝试这个:

$v = Validator::make($request->all(), [
    'email' => ['required',
    Rule::unique('<table_name>')->ignore(<your_table_id_to_ignore>),
    ]
]);

Works on Laravel 5.8. I don't know if it does work on lower versions of Laravel.

适用于 Laravel 5.8。我不知道它是否适用于较低版本的 Laravel。