Search code examples
phplaravelrouteslaravel-routinglaravel-exceptions

Laravel Exception 405 MethodNotAllowed


I'm trying to create a new "Airborne" test in my program and getting a 405 MethodNotAllowed Exception.

Routes

Route::post('/testing/{id}/airbornes/create', [
    'uses' => 'AirborneController@create'
]);

Controller

public function create(Request $request, $id)
{
    $airborne = new Airborne;

    $newairborne = $airborne->newAirborne($request, $id);

    return redirect('/testing/' . $id . '/airbornes/' . $newairborne)->with(['id' => $id, 'airborneid' => $newairborne]);
}

View

<form class="sisform" role="form" method="POST" href="{{ URL::to('AirborneController@create', $id) }}">
    {{ csrf_field() }}
    {!! Form::token(); !!}
    <button type="submit" name="submit" value="submit" class="btn btn-success">
        <i class="fas fa-plus fa-sm"></i> Create
    </button>
</form>

Solution

  • According to my knowledge forms don't have a href attribute. I think you suppose to write Action but wrote href. Please specify action attribute in the form that you are trying to submit.

    <form method="<POST or GET>" action="<to which URL you want to submit the form>">
    

    in your case its

    <form method="POST" ></form>
    

    And action attribute is missing. If action attribute is missing or set to ""(Empty String), the form submits to itself (the same URL).

    For example, you have defined the route to display the form as

    Route::get('/airbornes/show', [
        'uses' => 'AirborneController@show'
        'as' => 'airborne.show'
    ]);
    

    and then you submit a form without action attribute. It will submit the form to same route on which it currently is and it will look for post method with the same route but you dont have a same route with a POST method. so you are getting MethodNotAllowed Exception.

    Either define the same route with post method or explicitly specify your action attribute of HTML form tag.

    Let's say you have a route defined as following to submit the form to

    Route::post('/airbornes/create', [
            'uses' => 'AirborneController@create'
            'as' => 'airborne.create'
        ]);
    

    So your form tag should be like

    <form method="POST" action="{{ route('airborne.create') }}">
    //your HTML here
    </form>