skip to Main Content

i want to call route resource with ajax, when i put type as delete i got error (exception "SymfonyComponentHttpKernelExceptionMethodNotAllowedHttpException")
and given message (message "The DELETE method is not supported for this route. Supported methods: GET, HEAD, POST.").function almost work beacuse after make refresh the status also change but i am the above error.

route :

        Route::resource('category', ArtistCategoryController::class);

controller :

 public function destroy($id)
{
    $category = ArtistCategory::findOrFail($id);
    $deleteResponse = $category->update([
       'status'=>'d'
    ]);
    if ($deleteResponse) {
        deleteMessage();
        return redirect()->back();
    } else
        errorMessage();

}

view :

 <a href="" class="categoryDelete" data-id={{ $category->id}} ><i class="far fa-trash-alt" style="color: #b21f2d"></i></a>

ajax:

<script>
    $(".categoryDelete").on('click', function (e) {
        e.preventDefault();
        let id = $(this).data('id')
        // console.log(id)
        $.ajax({
            url: '/artist/category/'+id,
            type: 'DELETE',
            data:{"id": id, "_token": "{{ csrf_token() }}"},
            success: function (data)
            {
                alert(data)
            },
            error: function (e){
                alert(e)
            }
        });
    })
</script>

2

Answers


  1. Chosen as BEST ANSWER

    solved it with some changes in destroy method because i have used return return redirect()->back();it gives error and this is unacceptable

    updated

       public function destroy($id): IlluminateHttpJsonResponse
    {
        $category = ArtistCategory::findOrFail($id);
        $deleteResponse = $category->update([
           'status'=>'d'
        ]);
        if ($deleteResponse) {
            return response()->json([
                'data' => [
                    'id' => $id
                ],
                'status' => 'success',
            ]);
        } else
        {
            return response()->json([
                'data' => [
                    'id' => $id
                ],
                'status' => 'error',
                'message' => __("Couldn't Delete. Please Try Again!")
            ], 500);
        }
    
    }
    

  2. You need to set the csrf token in the header. Have a look at the docs in the bottom of the page: https://laravel.com/docs/8.x/csrf#csrf-x-csrf-token

    Create a meta tag with the token like this:

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

    And grap it like this:

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search