Delete method with Sweet Alert in Laravel

后端 未结 5 2075
我在风中等你
我在风中等你 2020-12-16 07:10

I\'m testing a method using Sweet Alert, to improve the messages issued by the Javascript alert method with the laravel framework.

1 - I downloaded the files sweetal

相关标签:
5条回答
  • 2020-12-16 07:42

    I think my code is closer to the Laravel framework, it has CSRF and it uses the Delete method; also it is more easy to integrate.

    Laravel 8 and SweetAlert 2

    UserController:

    public function destroy(User $user)
    {
        $user->delete();
        toast('Your file has been deleted !', 'success');
        return redirect(route('user.index'));
    }
    

    Delete html form: bootstrap used for css classes

    <form id="delete-user-form" action="{{route('user.destroy',$user)}}" method="POST">
        @csrf
        @method('DELETE')
        <button onclick="return false" id="delete-user" class="btn btn-danger">Delete</button>
    </form>
    

    jQuery

     $('#delete-post').on('click', function (e) {
                e.preventDefault();
                let id = $(this).data('id');
                Swal.fire({
                    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!'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $('#delete-post-form').submit();
                    }
                })
            });
    
    0 讨论(0)
  • 2020-12-16 07:49

    I have implemented this code into my laravel project and my route is resource route for destroy. This code is worked for me. As in above comment location.reload() help me and I put it into code...plz try and let me know...it worked for you or not...

    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    //.deletebutton is the class name in button
    <script>
        $('.deletebutton').on('click', function () {
            // return confirm('Are you sure want to delete?');
            event.preventDefault();//this will hold the url
            swal({
                title: "Are you sure?",
                text: "Once clicked, this will be softdeleted!",
                icon: "warning",
                buttons: true,
                dangerMode: true,
            })
            .then((willDelete) => {
                if (willDelete) {
                    swal("Done! category has been softdeleted!", {
                        icon: "success",
                        button: false,
                    });
                location.reload(true);//this will release the event
                } else {
                    swal("Your imaginary file is safe!");
                }
            });
        });
    </script>
    
    0 讨论(0)
  • 2020-12-16 07:51

    I have implemented this code in my laravel project and delete data by using route name with slug. This code is working for me. And i also delete row from table without reload() by using with id. So try this code let me know it's working for you or not.

     $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    
    function confirmDelete(slug) {
        swal({
                title: "Are you sure!",
                type: "error",
                confirmButtonClass: "btn-danger",
                confirmButtonText: "Yes!",
                showCancelButton: true,
            })
            .then((willDelete) => {
                if (willDelete.value == true) {
                    var url = '{{ route("instrument.delete", ":slug") }}';
                    url = url.replace(':slug', slug);
                    $.ajax({
                        url: url,
                        type: "POST",
                        data: {
                            '_method': 'DELETE'
                        },
                        success: function (data) {
                            if (data.status == 1) {
                                swal({
                                    title: "Success!",
                                    type: "success",
                                    text: "Instrument has been deleted \n Click OK",
                                    icon: "success",
                                    confirmButtonClass: "btn btn-outline-info",
                                });
                                $('#tr' + data.slug).remove();
                            }
    
                        },
                        error: function (data) {
                            swal({
                                title: 'Opps...',
                                text: data.message,
                                type: 'error',
                                timer: '1500'
                            })
                        }
                    })
                }
            });
    }
    
    0 讨论(0)
  • 2020-12-16 07:57

    You are Performing action on button click irrespective of whether you confirm or cancelled the deletion.

    <a href="" class="button" data-id="{{$user->id}}">Delete</a>
    

    Jquery and Ajax:

    $(document).on('click', '.button', function (e) {
        e.preventDefault();
        var id = $(this).data('id');
        swal({
                title: "Are you sure!",
                type: "error",
                confirmButtonClass: "btn-danger",
                confirmButtonText: "Yes!",
                showCancelButton: true,
            },
            function() {
                $.ajax({
                    type: "POST",
                    url: "{{url('/destroy')}}",
                    data: {id:id},
                    success: function (data) {
                                  //
                        }         
                });
        });
    });
    

    And:

    public function destroy(Request $request)
    {
        User::find($request->id)->delete();
        return redirect()->route('users.index')
                        ->with('success','User deleted successfully');
    }
    
    0 讨论(0)
  • 2020-12-16 08:03

    in the view :

    <button onclick="deleteItem(this)" data-id="{{ $user->id }}">Delete</button>
    

    in the Jquery and Ajax :

    <script type="application/javascript">
    
            function deleteItem(e){
    
                let id = e.getAttribute('data-id');
    
                const swalWithBootstrapButtons = Swal.mixin({
                    customClass: {
                        confirmButton: 'btn btn-success',
                        cancelButton: 'btn btn-danger'
                    },
                    buttonsStyling: false
                });
    
                swalWithBootstrapButtons.fire({
                    title: 'Are you sure?',
                    text: "You won't be able to revert this!",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, delete it!',
                    cancelButtonText: 'No, cancel!',
                    reverseButtons: true
                }).then((result) => {
                    if (result.value) {
                        if (result.isConfirmed){
    
                            $.ajax({
                                type:'DELETE',
                                url:'{{url("/user/delete")}}/' +id,
                                data:{
                                    "_token": "{{ csrf_token() }}",
                                },
                                success:function(data) {
                                    if (data.success){
                                        swalWithBootstrapButtons.fire(
                                            'Deleted!',
                                            'Your file has been deleted.',
                                            "success"
                                        );
                                        $("#"+id+"").remove(); // you can add name div to remove
                                    }
    
                                }
                            });
    
                        }
    
                    } else if (
                        result.dismiss === Swal.DismissReason.cancel
                    ) {
                        swalWithBootstrapButtons.fire(
                            'Cancelled',
                            'Your imaginary file is safe :)',
                            'error'
                        );
                    }
                });
    
            }
    
        </script>
    

    in the Controller:

    public function destroy(User $user, Request $request, $id)
        {
            if ($request->ajax()){
    
                $user = User::findOrFail($id);
    
                if ($user){
    
                    $user->delete();
    
                    return response()->json(array('success' => true));
                }
    
            }
        }
    

    in the Route

    Route::delete('/user/delete/{id}','UserController@destroy');
    
    0 讨论(0)
提交回复
热议问题