【发布时间】:2021-08-07 21:12:56
【问题描述】:
所以我想让管理员可以更改任何用户的密码。但我得到了这个错误
在 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">×</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>
【问题讨论】:
-
看起来数据库中不存在具有该 ID 的用户。如果您将
find()更改为findOrFail(),您应该得到一个强调这一点的错误。 -
User::find($id)是null,所以不能调用update,因为null->update(...)无效...$id是什么?您的数据库中是否有 ID 为$id的用户? -
@TimLewis 实际上我想调用管理员想要更改的用户的“ID”,但我不知道该怎么做,先生,您能告诉我该怎么做吗?
-
请看下面的答案。字符串
/admin/{id}/reset/password与您的action="..."无效,它应该是action="{{ url('/admin/1/reset/password') }}"或action="{{ route('resetPassword', ['id' => 1]) }}",传递预期的id(以1为例,但您需要定义正确的id,来自$id等变量,或来自用户,如$user->id等) -
@TimLwis 非常感谢先生!感谢您的宝贵时间
标签: laravel