我尝试授予用户更改(更新)他们在面板中的信息的权限,我也希望让他们更改他们的电子邮件地址以及他们的密码但是可选,例如他们可能只想更改他们的名字而不是更改电子邮件地址或密码的验证方法是什么?
我的验证当前是这样但会返回错误,电子邮件地址是相同的:
public function update(Request $request, $id)
{
$user = User::find($id);
$this->validate($request, array(
'name' => 'required|string|max:255',
'email' => 'nullable|string|email|max:255|unique:users',
'gender' => 'required|string',
'password' => 'nullable|string|min:6|confirmed',
));
$user = User::find($id);
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->gender = $request->input('gender');
$user->password = $request->input('password');
$user->save();
Session::flash('success', 'Your information was successfully updated.');
return redirect()->route('users.list', $user->id);
}
答案 0 :(得分:4)
来自documentation,您可以在验证中忽略当前用户的电子邮件地址:
'email' => Rule::unique('users')->ignore($user->id)
如果您的表使用的主键列名不是id,则可以在调用ignore方法时指定列的名称:
'email' => Rule::unique('users')->ignore($user->id, 'user_id')
所以,
$this->validate($request, array(
'name' => 'required|string|max:255',
'email' => [
'required','nullable','string','email','max:255',
Rule::unique('users')->ignore($user->id),
],
'gender' => 'required|string',
'password' => 'nullable|string|min:6|confirmed',
));
答案 1 :(得分:0)
您的用户更新应该是这样的:
public function update(Request $request, $id)
{
$user = User::find($id);
$this->validate($request, array(
'name' => 'required|string|max:255',
'gender' => 'required|string',
'password' => 'nullable|string|min:6|confirmed',
));
$user = User::find($id);
$user->name = $request->input('name');
$user->gender = $request->input('gender');
$user->password = $request->input('password');
$user->save();
Session::flash('success', 'Your information was successfully updated.');
return redirect()->route('users.list', $user->id);
}
然后你必须为更新新地址创建新页面。
答案 2 :(得分:0)
只需将其更改为以下名称字段验证:
$this->validate($request, array(
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users,'.$id,//validate for unique email except this id
'gender' => 'required|string',
'password' => 'required|string|min:6|confirmed',
));
答案 3 :(得分:0)
$this->validate($request, array(
'name' => 'required|string|max:255',
'email' => 'nullable|string|email|max:255|unique:users,email,id,'.$userId,
'gender' => 'required|string',
'password' => 'nullable|string|min:6|confirmed',
));
$ userId是给定用户的用户表的id
独特需要4个参数 唯一的:表,列,除了,idColumn
表格 - >表名
列 - > uniqueColumnName
除了 - >排除列名称
idColumn - >排除列的值