如何使用Laravel发出删除请求
问题描述:
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.
答
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>