donkey199024 2014-08-22 15:20
浏览 166

Laravel:验证唯一用户名问题

I have a noodle scratcher that I can't seem to figure out. I am validating for unique usernames and emails addresses. I have the following rules:

protected $rules = array(
    'username' => 'required|min:4|unique:users,username',
    'email'    => 'email|unique:users,email',
    'password' => 'min:6',
);

If I update a form that has the username (which is the same as it currently is), I get a The username has already been taken. error. If I do the same with the email, I get no error at all.

I know about adding the last param to the unique validation:

'unique:users,username,{{$id}}' or 'unique:users,username,'.$id

This doesn't work on the username. I get the same issue.

I can't figure out why this works for the email, but not the username.

Anyone had a similar issue or know where I am going wrong?

Many thanks,

  • 写回答

1条回答 默认 最新

  • doupi6737 2014-08-22 16:16
    关注

    The most likely reason is because $id is probably being pulled in through your URI, so it is not part of Input::all().

    To have it validated you would need to either include a hidden "id" field in your form or request, OR you would need to extend your repository or controller with a validate method which adds id back into the array of data being validated.

    /**
     * Validate
     *
     * @param $data
     * @param $id
     * @throws \ValidationException
     * @return boolean
     */
    public function validate($data, $id = null)
    {
        $rules = SomeModel::$rules;
        if(! is_null($id))
        {
           $data['id'] = $id;
           // Only add exclude rule to end of rule if you haven't included already
           $rules['username'] .= ',' . $data['id'];
        }
        $validator = \Validator::make($data, $rules);
        if($validator->fails()) {
            throw new \ValidationException($validator);
        }
        return TRUE;
    }
    

    Note: The ValidationException is not a normal exception, so either create this exception type or modify code to handle validation errors.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度