如何在更新时排除用户密码字段验证



我需要能够更新用户,而无需将其密码放入表单中。我已经完成了验证规则,但我不断收到错误:SQLSTATE[23000]:完整性约束违反:1048列"密码"不能为空。否则,更新会起作用。

这是我的控制器:

public function update(RequestsUserUpdateRequest  $request, $id)
{
User::findOrFail($id)->update($request->all())->except('password');
return redirect('backend/users')->with("message", "User was updated");
}

这是UserUpdateRequest:

public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required',
'email' => 'email|required|unique:users,email,' . $this->route('user'),
'password' =>'sometimes|required_with:password_confirmation|confirmed'];

}

这是我使用的表格:

<div class="form-group {{ $errors->has('name') ? 'has-error': '' }} ">
{!! Form::label('name') !!}
{!! Form::text('name',  null, ['class'=>'form-control']) !!}
@if($errors->has('name'))
<span class="help-block">{{$errors->first('name')}}</span>
@endif
</div>
<div class="form-group {{ $errors->has('email') ? 'has-error': '' }}">
{!! Form::label('email') !!}
{!! Form::text('email', null, ['class'=>'form-control']) !!}
@if($errors->has('email'))
<span class="help-block">{{$errors->first('email')}}</span>
@endif
</div>
<div class="form-group {{ $errors->has('password') ? 'has-error': '' }}">
{!! Form::label('password') !!}
{!! Form::password('password',  ['class'=>'form-control']) !!}
@if($errors->has('password'))
<span class="help-block">{{$errors->first('password')}}</span>
@endif
</div>
<div class="form-group {{ $errors->has('password_confirmation') ? 'has-error': '' }}">
{!! Form::label('password_confirmation') !!}
{!! Form::password('password_confirmation',  ['class'=>'form-control']) !!}
@if($errors->has('password_confirmation'))
<span class="help-block">{{$errors->first('password_confirmation')}}</span>
@endif
</div>

这里还有用户表的迁移:

public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}

我做错了什么?我在Laravel 7.5 上

问题发生的原因是始终设置"密码"-如果输入为空,则其值为null

一个解决方案是在FormRequest中运行验证器之前删除这个null值。

将以下内容添加到UserUpdateRequest:

/**
* Prepare the data for validation.
*
* @return void
*/
protected function prepareForValidation()
{
if($this->password == null) {
$this->request->remove('password');
}
}

相关内容

  • 没有找到相关文章

最新更新