简体   繁体   中英

Laravel 6 : Deleting user while still logged in

Currently i am developing a website. I am working on CRUD for one of my features and have had no problems up until the delete point. I am using bootstrap modal window as a warning window that pops up to clarify that you wish to delete your account. The code for that view and pop-up window looks like this:

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">
                <img src="{{ asset('/uploads/avatars/' . $user->avatar ) }}" style="width:100px; height:100px; float:left;
                margin-right:25px ">
                <strong>Delete {{$user->name}}'s account?</strong></div>
                <div class="card-body">
                <form action="delete" method="POST" enctype="multipart/form-data">
                {{csrf_field()}}
                <div class="form-group">
                    <label for="name">Account Email:</label>
                    <input type="text" name ="email" value="{{$user -> email}}" class="form-control" readonly>
                    <div class="form-group">
                    <div class="text-centre">
                    <p></p>
                    <button type="button" data_userid="{{$user->id}}" class="btn btn-danger" data-toggle="modal" data-target="#deleteModal">
                        Delete
                    </button>
                    </div>
                    </form>
                </div>
                </div>
            </div>
        </div>
    </div>
</div>


<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="deleteModalLabel">Are you sure?</h5>
        <form action="{{ route('delete', $user)}} " method="post">
        {{method_field('delete')}}
        {{csrf_field()}}
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>

      <div class="modal-body">
        Are you sure you want to permanetly delete your account?
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-dismiss="modal">No, cancel</button>
        <button type="submit" class="btn btn-danger">Yes, delete my account</button>
      </div>
      </form>
    </div>
  </div>
</div>

My Routes for this page and function look like so:

Route::get('/users/delete', 'Admin\UsersController@index')->name('delete');

Route::delete('admin/users/{user}', 'Admin\UsersController@destroy')->name('users.destroy');
    public function destroy($id,Request $request)
    {  
        $user = User::where("id","=",$id)->first();
        $user->delete($id);


        if ($user->delete()) 
        {
            return Redirect::route('home')->with('global', 'Your account has been deleted!');
        }

    }

ALso, whenever i try to access the page from a dropdown menu with route

 <a class="dropdown-item" href="{{ route('users.destroy', $user)}}">
                                        Delete Account

I am met with a blank page, i am sure this is down to the parameter. So just to clarify, Whenever the modal window pops up and the user hits "Yes, delete my account" nothing happens and the window stays open, and my routing to the page {{ route('users.destroy', $user)}} leads to a blank page. Any help is greatly appreciated!

This is how we try to delete Laravel

public function destroy(User $user)
{  
    $user->delete();
    return Redirect::route('home')->with('global', 'Your account has been deleted!');        
}

Change

<form action="{{ route('delete', $user)}} " method="post">

to

<form action="{{ route('delete', ['user' => $user]) }}" method="post">

in modal.

Also

<a class="dropdown-item" href="{{ route('users.destroy', $user)}}">Delete Account </a>

Does not work because it is a GET request. Deleting should be a DELETE request.

So you should open the modal with the click;

<a href="#" data-toggle="modal" data-target="#deleteModal" class="dropdown-item"> Delete Account</a>

According to your configuration it looks like you are using the wrong alias name for the form and anchor. You should switch them.

This is your route config:

Route::get('/users/delete', '[...]')->name('delete'); 
Route::delete('admin/users/{user}', '[...]')->name('users.destroy');

This is how you should use them:

  • On your <a/> you should use route('delete')
  • On your <form/> you should use route('users.destroy', ['user' => $userId]) .

And your delete action should look like this:

  • Delete the user
  • Logout the current user
  • Redirect somewhere
  public function destroy($id)
  {  
      User::find($id)->delete();
      Auth::logout();

      return Redirect::route('home')
          ->with('global', 'Your account has been deleted!');

  }

Hope this helps.

u can do it using ajax and sweetalert to it's more interactive for ui

in you blade file

@foreach($user as $u)
   <a href="javascript:void(0);" classs="delete" data-id="{{$u->id}}">Delete</a>
@endforeach

in your blade bottom you can call ajax request

<script>
  $(document).on('click','.delete',function()
  {
    var id = $(this).data('id');
    swal({
        title: 'Are you sure you want to delete this?',
        type: "warning",
        showCancelButton: true,
        confirmButtonClass: "btn btn-danger m-btn m-btn--pill m-btn--icon m-btn--air",
        confirmButtonText: '<span><i class="la la-thumbs-up"></i> Yes, Delete it!</span>',
        cancelButtonClass: 'btn btn-secondary m-btn m-btn--pill m-btn--icon m-btn--air',
        cancelButtonText: '<span><i class="la la-thumbs-down"></i>No, thanks</span>',
    }).then(function(e){
        if(e.value){
            $.ajax({
                url:"{{route('admin.document.delete')}}",
                type:'POST',
                headers:{ 'X-CSRF-Token' : jQuery('meta[name=csrf-token]').attr('content') },
                dataType:'json',
                data:{'id':id,_token: '{{csrf_token()}}'},
                success:function(response){   
                    var msg = response.msg;
                    if(response.status=='success'){
                        //here you can do whatever after delete msg
                        //for reload u can use - (location.reload);
                    }
                },

            });
        }
    });
}); 
</script>

and finally in your controller

public function destroy(Request $request)
{
   $id=$request['id'];
   $delete = manageMultipleDocument::find($id)->delete();
//optional
   $flashArr = array(
            'msg' => 'Document deleted successfully.',
            'status' => 'success'
        );
//optional
   $request->Session()->flash('succ_message',$flashArr);
//Required return any thing
   return $flashArr;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM