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

Time:03-17

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" >Save</button>
  <a type="button" href="/rabbits" >Cancel</a>
</form>

web.php routes

<?php
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\QuoteController;
use App\Http\Controllers\RabbitController;
use Illuminate\Support\Facades\Route;

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 App\Http\Controllers;

use App\Models\Rabbit;
use Illuminate\Http\Request;

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

CodePudding user response:

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.

  • Related