So my simple destroy don't work, what am I missing?

55 Views Asked by At

I'm trying to do the simpliest destroy with Laravel with a little modal, but it always appear a 404 Error.

I'm just doing in 2 parts, the index and the PostController, nothing else:

index (Button)

<button data-toggle="modal" data-target="#deleteModal" data-id="{{ $post->id }}" class="btn btn-danger"> Delete</button>

index (Modal DIV and Script)

<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="modalLabel"></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>

      <div class="modal-body">
        <p>Are you sure to delete this?</p>
      </div>
        
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <form method="POST" action="{{ route('post.destroy', 0) }}">
          @method('DELETE')
          @csrf
          <button type="submit" class="btn btn-danger">Delete</button>
        </form>
      </div>
    </div>
  </div>
</div>

<script>
  window.onload = function() {
    $('#deleteModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget)
    var id = button.data('id')
    var modal = $(this)
    modal.find('.modal-title').text('You're going to delete the POST:  ' + id)
  })
  }
</script>

PostController

public function destroy($id)
{
    $post = Post::findOrFail($id);

    $post->delete();

    return back()->with('status', '¡Post deleted!');
}
1

There are 1 best solutions below

2
Arleigh Hix On

I believe The second parameter of the helper method route should be an array while you have an integer 0.

Perhaps you mean to do something like this:

<form method="POST" action="{{ route('post.destroy', ['id' => $post->id]) }}">

(my apologies if the syntax is wrong, I'm more experienced with symfony/twig than laravel/blade)