简体   繁体   中英

Unable to delete record in laravel

I am trying to delete a record but unable to reach delete function in controller. Everything seems to be fine.

Tried with resource controller destroy function and also with custom route. But form is not posting to controller instead it's refreshing showing token and method in URL.

Previously, I was using Javascript function to confirm delete but it was also not working. So I switched to direct post.

Here is the Javascript code which was not submitting saying:

Uncaught TypeError: Cannot read property 'submit' of null

But, console.log(id) gives me correct id.

Even I am using this Javascript function everywhere in site but on this page it is not working.

function confirmDeleteUserCartItem(id)
{
  let choice = confirm("Are You Sure You Want To Delete This Item ?")
  if (choice)
  {
    document.getElementById('delete-usercart-item-' + id).submit();
  }
}

View: Tried with 2 routes

<form method="POST" action="{{ route('user.cart.delete', $item->id) }}">
 @csrf  
 @method('DELETE')
  <button class="btn btn-danger">Delete</button>
</form>
 <form method="POST" action="{{route('user.cart.destroy', $item->id)}}">
  @csrf  
  @method('DELETE')
 <button type="submit" class="remove">
  <i class="far fa-trash-alt"></i>
 </button>
 </form>

This is what I am getting in URL after clicking delete:

?_token=klYTBg3OBr0oLfTeS9tSGJwBepgLX8wtCsKRgMOR&_method=DELETE

Try this if it works. I hope if your route and controller destroy method is okay then it should work -

 <form method="POST" action="{{route('user.cart.destroy', $item->id)}}" 
                           onsubmit="return confirmDeleteUserCartItem()">
   @csrf  
   @method('DELETE')
   <button type="submit" class="remove">
       <i class="far fa-trash-alt"></i>
   </button>
 </form>

And you javascript method -

<script>
  function confirmDeleteUserCartItem()
  {

     let choice = confirm("Are You Sure You Want To Delete This Item ?")
     if (choice)
        return true;
     else
        return false;
  }
</script>

Fixed the issue. There was an another form tag in the html template which I was using in view. It was stopping the delete form to get submitted.

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