0
votes

I am using laravel 7. In my CRUD application, I am having trouble deleting a user record. I have tried a variety of methods which I have left commented out so that you can see what I tried. I am using Sweetalert2 for the confirmation call and when I click confirm, it redirects to the correct page but I do not get a success message nor is the record deleted from the database. I am new to Laravel so if anyone can spot where I may have gone wrong, I would sure appreciate it. Here are the following relevant codes. (EDIT OF CODE BELOW!!!) index.blade.php

@extends('layouts.admin')
@section('content')
<div class="container-fluid mt-5">
    <!-- Heading -->
    <div class="card mb-4 wow fadeIn">
      <!--Card content-->
      <div class="card-body d-sm-flex justify-content-between">
        <h4 class="mb-2 mb-sm-0 pt-1">
          <a href="https://mdbootstrap.com/docs/jquery/" target="_blank">Inicio</a>
          <span>/</span>
          <span>Registered Users</span>
        </h4>
      </div>
    </div>
    <!-- Heading -->
    <!--Grid row-->
      <!--Grid column-->
      <div class="row">
        <!--Card-->
        <div class="col-md-12 mb-4">
          <!--Card content-->
          <div class="card">
            <!-- List group links -->
             <div class="card-body">
                 <h5>Users Online:
                     @php $u_total = '0'; @endphp
                     @foreach ($users as $user)
                        @php
                            if($user->isUserOnline()) {
                                $u_total = $u_total + 1;
                            }
                        @endphp
                     @endforeach
                     {{ $u_total }}
                 </h5>
                <table id="datatable1" class="table table-bordered">
                    <thead>
                        <tr>
                           <th>Id</th>
                           <th>Name</th>
                           <th>Email</th>
                           <th>Role</th>
                           <th class="text-center">Online/Offline</th>
                           <th class="text-center">Banned/Unban</th>
                           <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($users as $user)
                         <tr>
                         <input type="hidden" name="id" value="{{ $user->id }}">
                         <td>{{ $user->id }}</td>
                         <td>{{ $user->name }}</td>
                         <td>{{ $user->email }}</td>
                         <td>{{ $user->role_as }}</td>
                         <td>
                            @if($user->isUserOnline())
                                <label class="py-2 px-3 badge btn-success" for="">Online</label>
                            @else
                                <label class="py-2 px-3 badge btn-warning" for="">Offline</label>
                            @endif
                         </td>
                         <td>
                            @if($user->isBanned == '0' )
                                <label class="py-2 px-3 badge btn-primary">Not Banned</label>
                            @elseif($user->isBanned == '1')
                            <label class="py-2 px-3 badge btn-danger">Banned</label>
                            @endif
                        </td>
                             <td>
                             <a class="badge badge-pill btn-primary px-3 py-2" href="{{ url('role-edit/'.$user->id) }}">Editar</a>

                             <a class="delete badge badge-pill btn-danger px-3 py-2" data-toggle="modal" href="{{ url('user-delete/'.$user->id) }}" data-target="#delete" data-id="{{ $user->id }}">Borrar</a>
                             </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
                {{-- <div>
                {{ $users->links() }}
                </div> --}}
            </div>
            <!-- List group links -->
          </div>
        </div>
        <!--/.Card-->
      </div>
      <!--Grid row-->
  </div>
@endsection
@section('scripts')
<script>
    $(document).ready(function() {
        $(document).on('click', '.delete', function (e) {
            e.preventDefault();
            var id = $(this).data('id');
            swal.fire({
                    title: "¿Estás Seguro/a?",
                    text: "¡No podrás revertir esto!",
                    icon: 'warning',
                    showCancelButton: true,
                    cancelButtonText: 'Cancelar',
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Sí, Borralo!'
                },
                function() {
                    $.ajax({
                        type: "POST",
                        url: "{{url('/user-delete/{id}')}}",
                        data: {id:id},
                        success: function (data) {
                                    //
                            }
                    });
            });
});
});
</script>
@endsection

Within my web.php (relevant code only)

Route::group(['middleware' => ['auth', 'isAdmin']], function () {
    Route::get('/dashboard', function () {
        return view('admin.dashboard');
    });

    Route::get('registered-user', 'Admin\RegisteredController@index');
    Route::delete('/user-delete/{id}', 'Admin\RegisteredController@destroy');
    Route::get('registered-empresa', 'Admin\EmpresaController@index');
    Route::get('registered-empleado', 'Admin\EmpleadoController@index');
    Route::get('role-edit/{id}', 'Admin\RegisteredController@edit');
    Route::put('role-update/{id}', 'Admin\RegisteredController@updaterole');
    Route::post('save-empresa', 'Admin\EmpresaController@store');
    Route::get('/edit-empresa/{id}', 'Admin\EmpresaController@edit');
    Route::put('/empresa-update/{id}', 'Admin\EmpresaController@update');
    Route::get('/edit-empleado/{id}', 'Admin\EmpleadoController@edit');
    Route::put('/empleado-update/{id}', 'Admin\EmpleadoController@update');
    Route::post('save-empleado', 'Admin\EmpleadoController@store');
});

RegisteredController.php (delete function only)

public function destroy(Request $request, $id)
    {
        // $user = User::findOrFail($id)->delete();
        // return redirect()->back()->with('status', 'Usuario ha sido borrado.');


        // $user = User::find($id);
        // $user->delete();
        // return redirect()->back()->with('status', 'Usuario ha sido borrado.');

        User::destroy($id);
    }

EDIT!!! I changed the way I am calling the sweetalert2 but am still getting errors. I changed my delete button in index.blade.php to

<a class="delete badge badge-pill btn-danger px-3 py-2" onclick="deleteConfirmation({{ $user->id }})">Borrar</a>

In the same file, I changed the script to the following:

 function deleteConfirmation(id) {
        swal.fire({
            title: "Borrar?",
            text: "¿Estás seguro/a?",
            icon: "warning",
            showCancelButton: !0,
            confirmButtonText: "Sí,Borralo!",
            cancelButtonText: "Cancelar",
            reverseButtons: !0
        }).then(function (e) {

            if (e.value === true) {
                var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');

                $.ajax({
                    type: 'POST',
                    url: "{{url('/user-delete')}}/" + id,
                    data: {_token: CSRF_TOKEN},
                    dataType: 'JSON',
                    success: function (results) {

                        if (results.success === true) {
                            swal.fire("Done!", results.message, "success");
                        } else {
                            swal.fire("Error!", results.message, "error");
                        }
                    }
                });

            } else {
                e.dismiss;
            }

        }, function (dismiss) {
            return false;
        })
    }

I also removed the .ready function as it was causing a conflict with sweetalert2

My Delete function in my RegisteredController now looks like this:

public function delete($id)
    {
        $delete = User::where('id', $id)->delete();

        // check data deleted or not
        if ($delete == 1) {
            $success = true;
            $message = "Usuario borrado exitosamente";
        } else {
            $success = true;
            $message = "Usuario no encontrado";
        }

        //  Return response
        return response()->json([
            'success' => $success,
            'message' => $message,
        ]);
    }
}

And in my web.php, I changed the route to:

Route::post('/user-delete/{id}', 'Admin\RegisteredController@delete');

The sweet alert now pops up and when I click delete, I get the console error:

POST http://ecomsivendo.test/user-delete/4 419 (unknown status)
2
I tried dd and var_dump but am not seeing any output. It should show up in my browser I assume. :)Erik James Robles
OK. I am changing the way I envoke the sweetalert2. I will keep you posted.Erik James Robles
check my updated answer.Andy Song
I think it's because you have a DELETE route defined in Route::delete('/user-delete/{id}', 'Admin\RegisteredController@destroy'); and you are sending POST request using jQuery. You must also change type: "POST" to type: "DELETE". I am not sure though.dcangulo

2 Answers

1
votes

You also need the headers section for jquery ajax calls.

$.ajax({
   type: "POST",
     headers: {
     'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  },
//.......

Also make sure you have the meta tag in the <head> on the page.

<meta name="csrf-token" content="{{ csrf_token() }}">
0
votes

Thank you for all those who tried to help me on this. I ended up giving the code another overhaul and this is what I had to do to get it to work. I had to change my ajax request in the index.blade.php

function deleteConfirmation(id) {
        swal.fire({
            title: "Borrar?",
            text: "¿Estás seguro/a?",
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "Sí,Borralo!",
            cancelButtonText: "Cancelar"
        }).then(function (e) {

            if (e.value === true) {
                var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
                $.ajax({
                    type: 'POST',
                    url: "{{url('/user-delete')}}/" + id,
                    headers: {
                    'X-CSRF-TOKEN': '<?php echo csrf_token() ?>'
                    },
                    data: {"id": id, _method: 'delete'},
                    dataType: 'JSON',
                    success: function (results) {


                        if (results.success === true) {

                            swal.fire("¡Hecho!", results.message, "success");
                            setTimeout(function() {
                                location.reload();
                            }, 1000);

                        } else {
                            swal.fire("¡Error!", results.message, "error");
                        }
                    }
                });

            } else {
                e.dismiss;
            }

        }, function (dismiss) {
            return false;
        })
    }

I am not happy with the setTimout function to get the page to reload and if someone can offer a better solution to avoid reload, I would really appreciate it. in the controller, I had to change the delete function to the following:

public function delete($id)
    {
        $delete = User::where('id', $id)->delete();


        // check data deleted or not
        if ($delete == 1) {
            $success = true;
            $message = "Usuario borrado exitosamente";
        } else {
            $success = true;
            $message = "Usuario no encontrado";
        }

        //  Return response
        return response()->json([
            'success' => $success,
            'message' => $message,
        ]);
    }

And finally in my web.php, I have the route as:

Route::delete('/user-delete/{id}', 'Admin\RegisteredController@delete');

like I mentioned earlier, I feel like the setTimeout is a hack and I would prefer something a bit more elegant.

In the end, the code does what it is supposed to do and that is delete the entry and update the view.