How to make a delete request with Laravel

≯℡__Kan透↙ 提交于 2020-12-25 02:33:30

问题


I am not using resource controller.

The route:

Route::delete('/deleteTag/{tag}','Controller2@deleteTag');

The controller function:

public function deleteTag(Tag $tag){
  $Tag = Tag::where('id', $tag->id)->get()->first();
  $Tag->delete();
  return redirect()->action('Controller2@main');
}

The call:

<form method="delete" action="http://***/public/deleteTag/{{$tag->id}}"> 
    {!! Form::token() !!} 
    <button type="submit">delete</button>
</form>

The program returns a MethodNotAllowedHttpException.

Thank you.


回答1:


You may try this (Notice the hidden _method input):

<form method="post" action="http://***/public/deleteTag/{{$tag->id}}"> 
    {!! Form::token() !!}
    <input type="hidden" name="_method" value="DELETE">
    <button type="submit">delete</button>
</form>

Check Form Method Spoofing.

Update:

In the latest versions of Laravel, it's possible to use blade directives for csrf and method in the form, for example:

<form method="post" action="..."> 
    @csrf
    @method('DELETE')
    <button type="submit">delete</button>
</form>



回答2:


It's better to change your route to this mode:

Route::resource('tags','TagController');

You should register a resourceful route to the controller. This single route declaration creates multiple routes to handle a variety of RESTful actions on the Tag resource. Remember, since HTML forms can't make PUT, PATCH, or DELETE requests, you will need to add a hidden _method field to spoof these HTTP verbs.

<input type="hidden" name="_method" value="DELETE">

or add this in your form

{{method_field('DELETE')}}


来源:https://stackoverflow.com/questions/44888433/how-to-make-a-delete-request-with-laravel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!