MHO
MHO

Reputation: 23

Laravel Vue Axios - Axios DELETE Request becomes GET Request

I'm getting a particular error and can't understand where the problem is.

No more explanations, code will illustrate it better than me :

Here are my routes :

Route::get('/', 'HomeController@index')->name('home');
Route::delete('home/{home}', 'HomeController@destroy')->name('home.destroy');

Here is my homeController :

class HomeController extends Controller
{
    public function index()
    {
        return view('view');
    }

    public function destroy()
    { 
        ddd('Hello World');
    }
}

Here is my view 'view.blade.php' :

@extends('layouts.layout')

@section('content')
    <component></component>
@endsection

Here is my layout :

<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta name="base-url" content="{{ url('/') }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    @yield('styles')

</head>
<body>

    <div id="app">

        @yield('content')

    </div>

    <!-- Scripts -->
    <script src="{{ mix('js/app.js') }}"></script>


    @yield('scripts')

</body>
</html>

Here is my bootstrap.js :

window._ = require('lodash');

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';


let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) 
{
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} 
else 
{
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

Here is my app.js :

require('./bootstrap');

window.Vue = require('vue');

Vue.prototype.baseUrl = document.head.querySelector('meta[name="base-url"]').content;
Vue.component('component', require('./components/ComponentComponent.vue').default);


const app = new Vue({
    el: '#app',
});

And here is my component :

<template>
    <button v-on:click="delete()">BUTTON</button>
</template>

<script>
    export default {
        methods: {
            delete() 
            {

                if ( confirm('Confirm ?') ) 
                {

                    axios.delete(`${this.baseUrl}/home/6`)
                    .then( (response) =>
                    {
                        console.log('Succeeded');
                    })
                    .catch( (error) => 
                    {
                        console.log('Failed');
                    });
                }
            }
        },
        created() 
        {
            this.$nextTick( () =>
            {
            });
        }
    }
</script>

What I actually have is a console.log message : "Succeeded" but as a response I get a page full of Ignition elements giving the error :

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException

The GET method is not supported for this route. Supported methods: DELETE.

When I change delete into get in my route : I get the error

DELETE http://test.test/home/6 404 (Not Found)

Like I'm really sending a DELETE Request but at a given time, it changes in a GET request Type... Inexplicable...

No need to say that I need serious help here, thank you for helping !

Upvotes: 0

Views: 2528

Answers (1)

Wojo
Wojo

Reputation: 65

Have you tried using a resource controller? https://laravel.com/docs/5.7/controllers#resource-controllers

Also you should follow the rules of the REST API. So a get request would be: http://test.test/home?id=6 A delete request would be: http://test.test/home/6

So in axios you want to use parameters when you send the get request to

axios.get('/home', {
    params: {
      id: 6
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .finally(function () {
    // always executed
  });  

But a delete request would go to 'http://test.test/home/' + id

https://github.com/axios/axios

I believe that because when you change the DELETE request http://test.test/home/6 to a GET request Laravel is looking for PUT, PATCH, DELETE this is why you are getting this error:

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException

The GET method is not supported for this route. Supported methods: PUT, PATCH, DELETE.

In your index method here:

public function index()
    {
        $id = $request->input('id');
        # DO SOMETHING WITH THIS ID HERE
        return view('view')->with(['data' => 'WHATEVER YOU DID ABOVE']);
    }

Is where you would handle this id parameter to fetch the id of 6.

https://laravel.com/docs/5.7/requests#retrieving-input

OR

You could add this to your controller:

public function show($id)
    {

    }

and than route to it:

Route::get('/{id}', 'HomeController@show')->name('home');

https://laravel.com/docs/4.2/routing#route-parameters

// Have you tried this way of doing the Axios delete?

axios({
  method: 'delete',
  url: '/home/6'
}).then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .finally(function () {
    // always executed
  });  

Upvotes: 1

Related Questions