Search code examples
laravelaxioscruddelete-rowhttp-status-code-405

DELETE 405 (Method Not Allowed) - Laravel with Axios


Basically i am trying to delete a row using axios, but i keep getting DELETE 405 (Method Not Allowed)

This is my api route for delete:

Route::delete('/vehicles/{id}', [VehiclesController::class, 'destroy']);

In the controller:

public function destroy($id)
{
    
    $vehicleDelete = Vehicle::findOrFail($id);
    $vehicleDelete->delete();

    return response()->json([
        "status" => true
    ], 200);

}

The button in the front-end:

<button class = 'btn btn-danger' onclick = "deleteBtn(${item.id})">Delete</button>

I tried using console.log to see if the i get the correct id and it does get the correct.

And here is the axios function:

const deleteBtn = (id) => {
        axios.delete("api/vehicles/" + id)
        .then(response => {
                console.log(id);
            })
    }

Solution

  • After trying out almost everything here is the solution that i randomly came with:

    API Route:

    Route::delete('/vehicles/{id}', [VehiclesController::class, 'destroy']);
    

    Destroy method in the controller:

        public function destroy($id)
        {
    
        $vehicle = Vehicle::find($id);
    
        if(!$vehicle) {
            return response()->json(["error" => "Vehicle does not exist!!"]);
        }
    
        if($vehicle->delete()) {
            return response()->json(["success" => "Vehicle deleted!!"]);
        }
    
        return response()->json(["error" => "Something bad happened!!"]);
    
        }
    

    front-end button:

    <button class = 'btn btn-danger' onclick = "deleteBtn(${item.id})">Delete</button>
    

    And finally, the javascript function:

    const deleteBtn = (id) => {
            axios.delete(API.url + (API.routes.deleteVehicles.replace("{id}", id)))
            .then(response => {
                vehicleTable.innerHTML = "";
                drawVehicles();
            })
        }
    

    For reference here is the API object:

    const API = {
            url: 'http://127.0.0.1:8000/api',
            routes: {
                getVehicles: '/vehicles',
                deleteVehicles: '/vehicles/{id}',
                createVehicles: '/vehicles'
            }
        }