Reputation: 47
I have a problem using sweetalert in Laravel
how to make a confirmation alert using Alert::question
to delete data in the table?
this is my code, but the alert appear after the data was deleted, how to fix this problem?
public function delete($id)
{Alert::question('Benar Ingin Hapus data?','data tidak dapat dikembalikan')->persistent('Close');
DB::table('daftar_pelanggans')->where('id',$id)->delete();
return redirect()->back();}
this is the delete button view.blade
<td>
<a href="{{ url('pages/daftar_pelanggan/edit/'.$pelanggan->id) }}" class="btn btn-sm btn-primary">
<i class="fa fa-edit"></i></a>
<a href="{{ url('daftar_pelanggan/delete/'.$pelanggan->id) }}"><button class="btn btn-sm btn-danger" ><i class="fa fa-trash"></i></button></a>
</td>
this is the routing web.php
Route::get('daftar_pelanggan/delete/{id}', [DaftarPelangganController::class,'delete'])->name('daftar_pelanggan.delete');
Upvotes: 1
Views: 1615
Reputation: 8138
You should use javascript code on the page that have the delete button/link to handle it(not PHP code).
an example use onclick on you delete link
<a href="javascript:void(0)" action="{{ url('daftar_pelanggan/delete/'.$pelanggan->id) }}" onclick="deleteData(this)"><button class="btn btn-sm btn-danger" ><i class="fa fa-trash"></i></button></a>
then add below code to the bottom of your blade/view after sweetalert js.
function destroyData(link) {
swal({
icon: 'warning',
title: 'Benar Ingin Hapus data?',
text: 'data tidak dapat dikembalikan',
buttons: ["No", "Yes"],
dangerMode: true,
})
.then(isClose => {
if (isClose) {
window.location = $(link).attr('action');
} else {
swal("Delete data canceled");
}
});
}
dont forget to change href
attribute to action
or another attribute name to prevent auto redirect go to href value after click.
Upvotes: 1