【问题标题】:Laravel Route resource destroy not workingLaravel Route 资源销毁不起作用
【发布时间】:2016-10-07 11:50:03
【问题描述】:

这是我的表格:

<form action="{{ route('invoice.destroy' , $invoice->id)}}" method="DELETE">
              <div class="modal-footer no-border">
                <button type="button" class="btn btn-info" data-dismiss="modal">No</button>
                <button type="submit" class="btn btn-primary">Yes</button>
               <input type="hidden" name="_method" value="DELETE" />

              </div>
              </form>

这是我的控制器:

public function destroy($id)
{
    $invoice = Invoice::find($id);
    if(!$invoice){
        return redirect()->route('invoice.index')->with(['fail' => 'Page not found !']);
    }
    $invoice->delete();
    return redirect()->route('invoice.index')->with(['success' => 'Invoice Deleted.']);
}

但是不能删除,问题出在哪里?如何解决这个问题?

【问题讨论】:

  • 您没有名为 _method 的隐藏参数。使用 Form::open()。
  • 不使用 Form::open 。我想通过这种方式解决。

标签: php laravel


【解决方案1】:

您需要对表单使用POST 方法并添加名称为_method 和值DELETEinput 元素。另外,添加令牌:

<form action="{{ route('invoice.destroy' , $invoice->id)}}" method="POST">
    <input name="_method" type="hidden" value="DELETE">
    {{ csrf_field() }}

    <div class="modal-footer no-border">
        <button type="button" class="btn btn-info" data-dismiss="modal">No</button>
        <button type="submit" class="btn btn-primary">Yes</button>
    </div>
</form>

【讨论】:

  • 是的,,,它正在工作。非常感谢@Alexey Mezenin
  • 对于编辑,您应该使用Get,但我想您需要的是update 操作,而不是editedit 只是显示一个表单)。对于update,您应该使用Put 方法。
【解决方案2】:

我认为您必须在表单中添加一个隐藏的输入,该输入将包含所使用的方法:

<form action="{{ route('invoice.destroy' , $invoice->id)}}" method="POST">
    <input type="hidden" name="_method" value="DELETE" />
</form>

阅读更多关于 Form method spoofing 的 Laravel 文档

【讨论】:

  • 注意表单的方法是POST而不是DELETE
【解决方案3】:

为了使PUTDELETE 方法工作,您需要一个额外的字段,因为在HTML 中只有POSTGET 是可能的(开箱即用)。

附加字段将使用代码:

{!! method_field('DELETE') !!}

所以您的表单将如下所示:

<form action="{{ route('invoice.destroy' , $invoice->id)}}" method="DELETE">
    {!! method_field('DELETE') !!}
    <div class="modal-footer no-border">
        <button type="button" class="btn btn-info" data-dismiss="modal">No</button>
        <button type="submit" class="btn btn-primary">Yes</button>
    </div>
</form>

【讨论】:

  • 你说的 {{ method_field('DELETE') }} 是什么意思??
  • 带有{!! method_field('DELETE') !!}(带感叹号)Laravel 将创建一个额外的隐藏输入文件。当提交表单时,Laravel 知道方法是 DELETE,执行Route::delete()
【解决方案4】:

另外,如果您使用刀片模板,您可以像这样添加方法字段: @method('删除')

【讨论】:

    【解决方案5】:

    更多 Laravel 方法可以做到这一点

    <form action="{{ route('invoice.destroy',$invoice->id)}}" method="POST">
        @method('DELETE')
        <button type="submit" class="btn btn-primary">Yes</button>
    </form>
    

    【讨论】:

    • 或更高版本中的@method('delete')
    猜你喜欢
    • 2021-11-25
    • 1970-01-01
    • 2014-09-05
    • 2021-06-01
    • 1970-01-01
    • 2017-12-18
    • 2016-07-23
    • 2017-04-11
    • 2018-09-06
    相关资源
    最近更新 更多