Yos Rafel
Yos Rafel

Reputation: 15

Call to a member function update() on null in laravel

So i want to make admin can change any user's password. but i got this error

Call to a member function update() on null

I have no idea what to do

this is my controller

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 !');
}

this my route

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

this is my view modal

<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>

Upvotes: 0

Views: 1414

Answers (1)

IGP
IGP

Reputation: 15786

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

You're not passing any id. The route picks up '{id}' as the id, then tries to find an User with the id '{id}' and finds none. (->first() returns null).

Just change that opening form tag's action attribute:

<form action="{{ route('resetPassword', ['id' => Auth::id()]) }}" method="POST"> (or instead of Auth::id() the user_id you're trying to update.


You could also use findOrFail($id) instead of find($id) so you'll get a clearer error message if an User is not found.

Upvotes: 2

Related Questions