1

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');

output : enter image description here

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, but your code not working for the cancel button, I have been solved for my problem, thank you for your answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.