简体   繁体   中英

Delete confirmation passes wrong user id in laravel, how to fix it?

I want that implement delete confirmation in laravel app when click on delete button. it works fine if there is no confirm dialoge, but does not work when I add javascript confirmation code.

here is my blade file

   <a href="{{ route('user.destroy', $user->id)}}" class="dropdown-item" onclick="
        var result = confirm('are you sure delete this?');
        if (result) {
            document.getElementById('delete_user').submit();
        }
        event.preventDefault();

        "><i class="icon-bin text-danger"></i> Delete</a>

      <form id="delete_user" action="{{ route('user.destroy', $user->id)}}" method="POST">
        @method('DELETE')
        @csrf
      </form>

I have created a form using native onsubmit function.

<form method="POST" action="{{route('user.destroy', ['user' => $user])}}" accept-charset="UTF-8" style="display: inline" onsubmit="return confirm('Are you sure wanted to delete it?')">
      @method('DELETE')
      @csrf
      <button type="submit" class="btn btn-danger btn btn-sm">
          Delete
      </button>
    </form>

I have been using it for may of my Projects its working fine for me. Can you try it.

And I have tried to find the bug in your code and i sorted it out.

when you add delete_user to the form and refer those id in a tag id of form need to be unique otherwise it will delete the delete the wrong record so I have fixed it by adding id (id of each record) like this delete_user_{{$user->id}}

so here is your code with bug fix.

<a href="{{ route('user.destroy', ['user' => $user])}}" class="dropdown-item" onclick="
      var result = confirm('are you sure delete this?');
      if (result) {
          document.getElementById('delete_user_{{$user->id}}').submit();
      }
      event.preventDefault();

      "><i class="icon-bin text-danger"></i> Delete</a>

    <form id="delete_user_{{$user->id}}" action="{{ route('user.destroy', ['user' => $user]) }}" method="POST">
      @method('DELETE')
      @csrf
    </form>

If you face any issues kindly comment below

Remove href attribute from <a> . And also onclick must be function.

<a class="dropdown-item" onclick="deleteUser(event)"><i class="icon-bin text-danger"></i> Delete</a>

Define delete function in the bottom of file.

<script>
function deleteUser(event){
  var result = confirm('are you sure delete this?');
  if (result) {
     document.getElementById('delete_user').submit();
  }
  event.preventDefault();

}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM