无法更新 Laravel 中的用户信息

Can't update user information in Laravel

在我当前的项目(学校管理系统)中,我想让管理员能够注册用户。例如,管理员可以创建课程和主题,我已经使用资源控制器设法做到了这一点。然而,我想我可以为用户做同样的事情,因为这个过程对我来说是一样的。即:我可以显示、编辑、创建、更新和删除用户。

但是,到目前为止,我 运行 遇到了几个问题。现在我可以创建用户,但不能更新它们。

这是我的代码:

web.php

Route::middleware(['auth', 'admin'])->group(function () {

  Route::get('/admin', 'HomeController@admin');

  Route::post('register', 'UserController@store');

  Route::resources([
      'admin/cursos' => 'CursoController',
      'admin/turmas' => 'TurmaController',
      'admin/semestres' => 'SemestreController',
      'admin/materias' => 'MateriaController',
      'admin/usuarios' => 'UserController',
  ]);

});

UserController.php

public function update(Request $request, $id)
{
  $rules = array(
    'name'      => 'required|string|max:255',
    'email'     => 'required|string|email|max:255|unique:users',
    'role'      => 'required|string',
    'password'  => 'required|string|min:6|confirmed',
  );

  $validator = validator::make(Input::all(), $rules);

  if ($validator->fails()) {
    // return dd();
    return Redirect::to('/admin/usuarios/' . $id . '/edit')
    ->withErrors($validator);
  } else {
    // store
    $user = User::find($id);
    $user->name       = Input::get('name');
    $user->email      = Input::get('email');
    $user->role       = Input::get('role');
    $user->password   = Input::get('password');
    $user->save();

    // redirect
    Session::flash('message', 'Sucesso!');
    return Redirect::to('/admin/usuarios');
  }

}

每次尝试更新用户信息时验证都失败。这里到底发生了什么?我对 Laravel 比较陌生,所以我现在有点迷路了。

您必须在电子邮件验证中排除用户 ID ($id),因为您使用 "unique" 规则。

你可以在这里查看指南 https://laravel.com/docs/5.6/validation#rule-unique

如果用户尝试在不更改电子邮件地址的情况下更新其信息时请求失败,则您需要额外的逻辑来忽略与电子邮件关联的用户 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:

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

应用于您的验证规则集,它看起来像:

$rules = array(
    'name'      => 'required|string|max:255',
    'email'     => [
        'required', 
        'string', 
        'email, 
        'max:255', 
        Rule::unique('users')->ignore(auth()->id())
     ],
    'role'      => 'required|string',
    'password'  => 'required|string|min:6|confirmed',
);