0

I'm migrating my app from laravel 4.2 to 5.7. I have this logic to delete a user: this action is triggred onclick

$.ajaxSetup({
    headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
})

$.ajax({
    type: "DELETE",
    url: "{{ URL::to('administrator/admin-delete') }}"+"/"+id
});

In my route file:

Route::delete('admin-delete', 'UsersController@removeAdminDelete');

and in my controller:

public function removeAdminDelete($id)
{
    $user = Admin::find($id);
    File::delete($user->photo);
    $user->delete();
    Session::flash('successDelete', "ok");
    if(Auth::user()->id == $id){
        Auth::user()->logout();
        return Redirect::to("administrator");
    }else{
        return Redirect::back();
    }
}

when i try to remove a user i get this error in my console:

DELETE my_delete_url 419 (unknown status)!!

After edit i get 404 error !!

Ryuujo
  • 613
  • 1
  • 9
  • 26
Youssef Boudaya
  • 123
  • 1
  • 2
  • 15

3 Answers3

4

A 419 error in Laravel means that you haven't provided a token for csrf.

As shown in the dos you can add a meta tag to the head of your page with the token in:

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

and then set up your ajax requests to include it all the time:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

NB Make sure you add the above code after you've pulled in jQuery and before you make the ajax request.


Furthermore, you should use delete and not resource for your route.

Change

Route::resource('admin-delete', 'UsersController@removeAdminDelete');

to

Route::delete('admin-delete/{id}', 'UsersController@removeAdminDelete');
Rwd
  • 34,180
  • 6
  • 64
  • 78
0

It seems it is related to csrf token. try to add csrf token in your ajax call like this:

<meta name="csrf-token" id="csrftoken" content="{{ csrf_token() }}">

and setup your ajax with this header:

$.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': $('#csrftoken').attr('content')
  }
});
0

before the closing form tag add this like so

<form action='' method='post'>
......
@csrf
</form>
Emeka Okafor
  • 427
  • 4
  • 10