laravel 5删除方法。 始终在RouteCollection.php第233行中的MethodNotAllowedHttpException:

laravel 5删除方法。 始终在RouteCollection.php第233行中的MethodNotAllowedHttpException:

问题描述:

This is my route

Route::delete('/customer_page/summary/{id}', 'ReservationController@delete_cart');

My controller function

public function delete_cart($id)
    {


        cart::findOrFail($id)->delete();

        return redirect('/customer_page/summary');
    }

My form

 @foreach($cart as $key => $val)
                          <tr>
                            <td>{{ $val->room_type }}</td>
                            <td>{{ $val->number_of_rooms }}</td>
                            <td>{{ $val->price }}</td>
                            <td>
                              <form action="/customer_page/summary/{{ $val->id }}" method="post">
                                {{ csrf_field() }}
                                <input type="hidden" name="_method" value="DELETE" />
                                <button type="submit" class="btn waves-effect red"><i class="material-icons">delete</i>delete</button>
                              </form>
                            </td>
                          </tr>
                        @endforeach

I don't know why I always keep getting that error

You need to set your method="POST" on your form, then inside of the form, use Laravel's method_field() helper: {{ method_field('DELETE') }}. Do not attempt to set your method to delete directly.

The other answer using the form helper package form laravel-collective will work fine too, but that's not included by default in Laravel anymore, so I thought it prudent to outline how to achieve this using raw HTML.

You need to change method on form, from POST to DELETE

You see on route you have defined as DELETE:

Route::delete('/customer_page/summary/{id}', 'ReservationController@delete_cart');

Do the following(RESTFUL)

Route::resource('reservations', 'ReservationController');

OR(NON RESTFUL)

Route::delete('delete/{id}',array('uses' => 'ReservationController@destroy', 'as' => 'My.route'));

Controller

public function destroy($id)
{
    $item = Reservation::findOrFail($id);
    $item->delete();

}

View

@foreach($reservations as $item)
    <tr>
        <td>{{ $item->description }}</td>

        <td>
            {{ Form::open(['method' => 'DELETE', 'route' => 'reservations.destroy', $item->id]) }}
                {{ Form::hidden('id', $item->id) }}
                {{ Form::submit('Delete', ['class' => 'btn btn-danger']) }}
            {{ Form::close() }}
        </td>
    </tr>
@endforeach

OR (for non restful)

{{ Form::open(['route' => ['My.route', $value->id], 'method' => 'delete']) }}
<button type="submit">Delete</button>
{{ Form::close() }}

If you are using the below

{!! Form::model($user,
['method' => 'DELETE',
'route' => ['users.destroy', $user->id],
]) !!}
{{ method_field('DELETE') }}

// then you form goes here

{{ method_field('DELETE') }}
{!! Form::close() !!}