I'm encountering an issue with sweetalert2 while using Laravel Vue for my app development. My goal is to have a confirmation modal pop-up when deleting a row from the database. However, whenever I click "Yes", the item is successfully removed. But if I click the cancel button, the modal closes and still deletes the entire row. This has left me feeling confused as this is my first time working with these frameworks, and I am eager to learn more about them.
Below is the code snippet from IndexComponent.vue:
methods: {
deletePost(id) {
this.$swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!',
closeOnCancel: true
}).then((result) => {
//send request to server
let uri = `/api/post/delete/${id}`;
axios.delete(uri).then(response => {
this.posts.splice(this.posts.indexOf(id), 1);
});
if (result.value) {
this.$swal(
'Deleted!',
'Your post has been deleted!',
'success'
)
}
})
}
}
This is the button
in my table cell that triggers the deletion functionality:
<td><button @click="deletePost(post.id)" class="btn btn-danger">Delete</button></td>
And here is the excerpt from PostController.php:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Resources\PostCollection;
use App\Post;
public function delete($id) {
$post=Post::find($id);
$post->delete();
return response()->json('Successfully deleted!');
}
All CRUD operations are functioning correctly, but the implementation of sweetalert2 seems to be resulting in multiple deletions. Can anyone offer some assistance on this matter?