php - Laravel中表单验证里unique在update时怎么排除当前记录呢?
巴扎黑
巴扎黑 2017-04-11 09:06:10
[PHP讨论组]

如下代码:

public function rules()
{
     return [
          'name'=>'unique:roles',
    ];
}

以上代码完成了自动验证name值是否唯一。这在新建一条记录时很有用,但是当更新记录且没有改变name值时,该条验证必定会检测到与自己冲突,怎么在update时排除掉自己呢?

巴扎黑
巴扎黑

全部回复(2)
阿神

https://laravel.com/docs/5.3/...

Forcing A Unique Rule To Ignore A Given ID:

Sometimes, you may wish to ignore a given ID during the unique check. For example, consider an "update profile" screen that includes the user's name, e-mail address, and location. Of course, you will want to verify that the e-mail address is unique. However, if the user only changes the name field and not the e-mail field, you do not want a validation error to be thrown because the user is already the owner of the e-mail address.

To instruct the validator to ignore the user's ID, we'll use the Rule class to fluently define the rule. In this example, we'll also specify the validation rules as an array instead of using the | character to delimit the rules:

use Illuminate\Validation\Rule;

Validator::make($data, [
    'email' => [
        'required',
        Rule::unique('users')->ignore($user->id),
    ],
]);

If your table uses a primary key column name other than id, you may specify the name of the column when calling the ignore method:

'email' => Rule::unique('users')->ignore($user->id, 'user_id')
高洛峰

你可以参照:Laravel 更新数据时在表单请求验证中排除自己,检查指定字段唯一性

路由

backend/user/{user}

实例

<?php

namespace App\Http\Requests\Backend\User;

use App\Http\Requests\Request;

class UpdateRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $id = $this->route('user'); //获取当前需要排除的id
        return [
            'email' => "required|email|unique:users,email,".$id,
        ];
    }
    
}

验证说明

unique:表名,字段,需要排除的ID

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号