Skip to content
Advertisement

Laravel 9 html form submit throws 405. Expects PUT, request is GET

I’m trying to create a simple CRUD application with Laravel 9. I’ve run into a problem with HTML forms. I’ve created a page where you can edit data on rabbits existing in my database.

My form

<form name="editRabbitForm" action="{{ url('/rabbit/update') }}" method="PUT">
  {{ csrf_field() }}
  <!-- here be input fields -->
  <button type="submit" class="btn btn-success">Save</button>
  <a type="button" href="/rabbits" class="btn btn-danger">Cancel</a>
</form>

web.php routes

<?php
use IlluminateSupportFacadesAuth;
use AppHttpControllersQuoteController;
use AppHttpControllersRabbitController;
use IlluminateSupportFacadesRoute;

Route::get('/rabbits', [RabbitController::class, 'index']);
Route::get('/rabbit/edit/{id}', [RabbitController::class, 'edit']);
Route::put('/rabbit/update', [RabbitController::class, 'update']);

RabbitController.php

<?php

namespace AppHttpControllers;

use AppModelsRabbit;
use IlluminateHttpRequest;

class RabbitController extends Controller
{
    public function index() {
        return view('rabbits.index', ['rabbits' => Rabbit::all()]);
    }

    public function edit($id) {
        return view('rabbits.edit', ['rabbit' => Rabbit::where('breed_id', $id)->first()]);
    }

    public function update(Request $request) {
        echo("SOME SORT OF RESULT!");
        var_dump($request);
    }
}

Before I even hit the controller I get an exception reading: The GET method is not supported for this route. Supported methods: PUT.

URL request as defined by Laravel

I really don’t get what I’m doing wrong in this scenario

Advertisement

Answer

As stated above in my comment:

To send a put request you will need to change the method to POST and add @method('PUT') in your form. This will insert a hidden input for the method. Laravel will then automatically route this request to the method specified by the put route in your routes file.

This is needed because as @ADyson writes, browsers are limited to GET and POST request.

And last but not least, browsers or in this case HTML forms are stupid. Maybe someday this will be changed, who knows.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement