User57
User57

Reputation: 2505

Laravel Delete Method: MethodNotAllowedHttpException in RouteCollection.php line 233:

I tried to delete the cart from a list. When I tried to delete it, it shows an Error. Below here is my code:

Web.php

Route::post('cart/delete/{id}','ProductController@deleteCart');

blade.php

<a href="{{ url('/cart/delete',$row->id) }}" class="remove_item">
    <i class="fa fa-times"></i>
</a>
    
<form action="{{ url('/cart/delete',$row->id)}}" method="POST" style="display: none;">
    {!! Form::hidden('id',$row->id) !!}
</form>

Controller.php

public function deleteCart($id){
    $cart = Cart::find($id);
    $cart->destroy();
    return Redirect::to('/shop-cart');
}

Upvotes: 1

Views: 2244

Answers (3)

Yasas Gunarathne
Yasas Gunarathne

Reputation: 893

Simply change the following line of code:

Route::post('cart/delete/{id}','ProductController@deleteCart');

into:

Route::get('cart/delete/{id}','ProductController@deleteCart');

Reason for this error is sending a GET request to a POST route. In your code you are sending a GET request by calling a URL.

<a href="{{ url('/cart/delete',$row->id) }}" class="remove_item">
   <i class="fa fa-times"></i>
</a>

Or otherwise if you want to keep the route as it is (as a POST route) just use the following code and make some adjustments accordingly:

<form  action="{{ url('/cart/delete') }}" method="POST" style="display: none;">
    {!! Form::hidden('id', $row->id) !!}
    <input type="submit" value="Submit">
</form>

And it is better to modify the route as follows as the '/{id}' part is not needed as we are sending the id along with the POST request:

Route::post('cart/delete','ProductController@deleteCart');

Import Http\Request into your controller using:

use Illuminate\Http\Request;

And update your controller function as follows:

public function deleteCart(Request $request){
    $cart = Cart::find($request['id']);
    $cart->destroy();
    return Redirect::to('/shop-cart'); 
}

But for this scenario GET route seems a good choice to avoid complexity.

Upvotes: 2

Onix
Onix

Reputation: 2179

The error say that there is no route like the one you try to call. you have a route like this in your route file : /cart/delete/{id} where expects an id, and you call this from your form /cart/delete?id=theid

Fix

Change this from your submit url : /cart/delete',$row->id)

To this: /cart/delete/{{$row->id}}

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

Remove a href link, because it will send GET request, instead of POST. Add submit button to the form:

<form  action="{{ url('/cart/delete/'.$row->id) }}" method="POST" style="display: none;">
    {!! Form::hidden('id', $row->id) !!}
    {!! Form::submit('delete') !!}
</form>

Upvotes: 0

Related Questions