【问题标题】:How do I call the laravel destroy function through an html form and javascript?如何通过 html 表单和 javascript 调用 laravel destroy 函数?
【发布时间】:2022-01-04 21:14:31
【问题描述】:

(我只是个初学者!!)

控制器:

public function destroy(Pessoa $pessoa)
{
    $pessoa->delete();
    return redirect("http://localhost:5500/index.html");
}

我可以使用帖子

 <form action="http://127.0.0.1:8000/api/pessoas" method="POST">

但是如何使用 delete 方法呢?

【问题讨论】:

  • 这能回答你的问题吗? use DELETE method in route with Laravel 5.4
  • 只需添加隐藏输入 &lt;input type="hidden" name="_method" value="delete" /&gt; 或在 Blade 中,@method('delete')
  • @WaseemAlhabash 我看到了这篇文章,但我使用 laravel 作为 API。问题是我想通过 html 删除列,使用
  • @miken32
    127.0.0.1:8000/api/pessoas" method="delete">

标签: php laravel


【解决方案1】:

您可以通过刀片添加csrfmethod

<form action="http://127.0.0.1:8000/api/pessoas" method="post">
   @csrf
   @method('DELETE')
</form>

或者,使用 Javascript Fetch:

fetch("http://127.0.0.1:8000/api/pessoas", {
    method: "DELETE",
    headers: {
        'Content-Type': 'application/json'
    },
})

【讨论】:

  • 这就是答案,谢谢!!就是不知道怎么用……(我在控制台试了一下,效果不错,但不知道怎么在应用中使用)
【解决方案2】:

这里是完整的例子:

<form action="{{ route('category.destroy', $category->id) }}" method="POST" onsubmit="return confirm('{{ trans('global.areYouSure') }}');" style="display: inline-block;">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="btn btn-xs btn-danger" value="Delete">

定义成路线:

Route::delete('/category/delete/{id}', 'CategoryController@destroy')->name('category.destroy');

控制器将如下所示:

public function destroy($id)
{
$category = Category::find($id);
$category->delete();

return back()->with('success', 'Item is deleted successfully');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多