首页 > 解决方案 > 在 laravel 中调用 null 上的成员函数 update()

问题描述

所以我想让管理员可以更改任何用户的密码。但我收到了这个错误

在 null 上调用成员函数 update()

我不知道该怎么做

这是我的控制器

public function resetPassword(Request $req, $id)
{
    $req->validate([
        'new_password' => ['required'],
        'new_confirm_password' => ['same:new_password'],
    ],
    [
        'new_password.required' => 'Password Baru Harus Diisi !',
        'new_confirm_password.same' => 'Password Baru Harus Sama Dengan Confirm Password !',
    ]);
    User::find($id)->update(['password'=> Hash::make($req->new_password)]);
    return redirect('/admin/list_user')->with('status', 'Password Berhasil di Ubah !');
}

这是我的路线

Route::put('/admin/{id}/reset/password', 'PageController@resetPassword')->name('resetPassword');

这是我的视图模式

<div class="modal fade" id="resetModal" tabindex="-1" role="dialog" aria-labelledby="resetModal" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Reset Password</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form action="/admin/{id}/reset/password" method="POST">
          {{csrf_field()}}
          {{ method_field('PUT') }}
          <div class="form-group">
            <label for="password">Password Baru</label>
            <input name="new_password" type="password" class="form-control" id="new_password" required>
          </div>
          <div class="form-group">
            <label for="password">Confirm Password</label>
            <input name="new_confirm_password" type="password" class="form-control" id="new_confirm_password" required>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-danger" data-dismiss="modal">Tutup</button>
          <button type="submit" class="btn btn-primary">Buat</button>
        </form>
      </div>
    </div>
  </div>
</div>
</div>

标签: laravel

解决方案


<form action="/admin/{id}/reset/password" method="POST">

你没有传递任何 id。该路由选择'{id}'id,然后尝试使用该 id'{id}'查找用户,但没有找到。(->first()返回null)。

只需更改该打开表单标签的 action 属性:

<form action="{{ route('resetPassword', ['id' => Auth::id()]) }}" method="POST">(或者代替您尝试更新Auth::id()的内容。user_id


您也可以使用findOrFail($id)代替,find($id)这样如果User未找到 an,您将收到更清晰的错误消息。


推荐阅读