user8705895
user8705895

Reputation:

Laravel Delete Functions is Not Working with Post Method

I am learning Php Laravel.I am using Laravel version 6.1. I am trying to do CRUD operations. My Insert , Update methods is working fine but when I tried to delete the records, I a getting following error .

The POST method is not supported for this route. Supported methods: GET, HEAD, PUT, PATCH, DELETE.

Here is my Route .

Route::resource('products','ProductController');

Here is my controller code .

 public function destroy(Product $product)
    {
        $product->delete();

        return redirect()->route('products.index')
                        ->with('success','Product deleted successfully');
    }

Here is index.blade.php code .

@extends('products.layout')

@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Laravel 5.8 CRUD Example </h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-success" href="{{ route('products.create') }}"> Create New Product</a>
            </div>
        </div>
    </div>

    @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
    @endif

    <table class="table table-bordered">
        <tr>
            <th>No</th>
            <th>Name</th>
            <th>Details</th>
            <th width="280px">Action</th>
        </tr>
        @foreach ($products as $product)
        <tr>
            <td>{{ ++$i }}</td>
            <td>{{ $product->name }}</td>
            <td>{{ $product->detail }}</td>
            <td>
                <form action="{{ route('products.destroy',$product->id) }}" method="POST">

                    <a class="btn btn-info" href="{{ route('products.show',$product->id) }}">Show</a>

                    <a class="btn btn-primary" href="{{ route('products.edit',$product->id) }}">Edit</a>

                    @csrf
                    @method('DELETE')

                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </td>
        </tr>
        @endforeach
    </table>

    {!! $products->links() !!}

@endsection

Here is the result when I clicked the delete button . enter image description here

Upvotes: 1

Views: 750

Answers (1)

Poldo
Poldo

Reputation: 1932

Put your method above @crsf

<form action="{{ route('products.destroy',$product->id) }}" method="POST">

       <a class="btn btn-info" href="{{ route('products.show',$product->id) }}">Show</a>

        <a class="btn btn-primary" href="{{ route('products.edit',$product->id) }}">Edit</a>

        @method('DELETE')
        @csrf

     <button type="submit" class="btn btn-danger">Delete</button>
 </form>

Upvotes: 2

Related Questions