【发布时间】:2020-07-27 00:07:24
【问题描述】:
我需要能够更新用户而无需将他的密码输入表单。我已经完成了验证规则,但我不断收到错误:SQLSTATE [23000]:完整性约束违规:1048 列“密码”不能为空。否则更新有效。
这是我的控制器:
public function update(Requests\UserUpdateRequest $request, $id)
{
User::findOrFail($id)->update($request->all())->except('password');
return redirect('backend/users')->with("message", "User was updated");
}
这是用户更新请求:
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
【问题讨论】:
-
表格上总是需要提供密码吗?
-
没有。仅在创建时。不更新。
-
但它总是显示在创建和更新的表单上?
-
是的,以防它仍然需要更新。
标签: laravel validation