use DELETE method in route with Laravel 5.4

我怕爱的太早我们不能终老 提交于 2019-11-29 06:22:08

If you click on an url it will always be a GET method.

Since you wish to define it as DELETE, you should remake it into a post form and add

<input type="hidden" name="_method" value="delete" />

in it. Like replace:

<a href="{{ url('/categories', ['id' => $category->id]) }}">
    <button class="btn btn-default">Delete</button>
</a>

with:

<form action="{{ url('/categories', ['id' => $category->id]) }}" method="post">
    <input class="btn btn-default" type="submit" value="Delete" />
    <input type="hidden" name="_method" value="delete" />
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

Same goes for PUT request.

Since Laravel 5.1 method_field:

<form action="{{ url('/categories', ['id' => $category->id]) }}" method="post">
    <input class="btn btn-default" type="submit" value="Delete" />
    {!! method_field('delete') !!}
    {!! csrf_field() !!}
</form>

Since Laravel 5.6 just with @ tag:

<form action="{{ url('/categories', ['id' => $category->id]) }}" method="post">
    <input class="btn btn-default" type="submit" value="Delete" />
    @method('delete')
    @csrf
</form>

Any method other than GET and POST requires you to specify the method type using a hidden form input. That's how laravel detects them. In your case you need to send the delete action using a form. Do this.

<table class="table">
    <thead>
    <th>Name</th>
    <th>Action</th>
    </thead>
    <tbody>
    @foreach ($categories as $category)
        <tr>
            <td>$category->name</td>
            <td>
                <form action="/categories/{{ $category->id }}" method="post">
                    {{ method_field('delete') }}
                    <button class="btn btn-default" type="submit">Delete</button>
                </form>
            </td>
        </tr>
    @endforeach
    </tbody>
</table>

For laravel 5.7 please look my example:

<form action="{{route('statuses.destroy',[$order_status->id_order_status])}}" method="POST">
 @method('DELETE')
 @csrf
 <button type="submit">Delete</button>               
</form>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!