【问题标题】:Laravel delete action inside foreach loopLaravel 在 foreach 循环中删除操作
【发布时间】:2014-06-05 19:27:39
【问题描述】:

对于显示的每个结果,我希望有一个关联的删除操作。

foreach 循环内我有:

{{ Form::open(array('route' => array('archive', $alert->id), 'role'=>'form')) }}

<table class="tablesorter table-responsive" id="alerts">
    <thead>
        <tr>
        <th class="header">ID</th>
        <th class="header">Archive</th>
    </tr>
  </thead>
  <tbody>
    @foreach($alert->alerts as $alert)
    <tr>
    <td><button type="submit" class="btn btn-warning" name="archive">Archive</button></td>
  </tr>
  @endforeach
</tbody>
</table>

{{ Form::close() }}

路线:

Route::post('agents/destroy/{id}', 
             array('as' => 'archive', 'uses' => 'AgentsController@postDestroy'));

销毁函数:

public function postDestroy($id)
    {
        $alert  = Alert::find($id);
        $alert->delete();

    }

当我dd($id) 时,它返回 null,就好像它没有从提交按钮中获取 'id'。

任何帮助将不胜感激。

【问题讨论】:

    标签: php laravel laravel-4 foreach


    【解决方案1】:

    HTML 不会将 ID 属性传递给 PHP,我会做你想做的事情:

    路线:

    Route::post('agents/destroy/{id}', array('as' => 'archive', 'uses' => 'blah@postDestroy'));
    

    表格:

    {{ Form::open(array('route' => array('archive', $alert->id), 'role'=>'form')) }}
        <td><button type="submit" class="btn btn-warning" name="archive">Archive</button></td>
    
    {{ Form::close() }}
    

    控制器/模型:

    public function postDestroy($id)
    {
        $alert  = Alert::find($id);
        $alert->delete();
    }
    

    据我所知,ID 属性仅真正用于选择 DOM 中的元素。

    编辑:

    更改以下内容:

    <table class="tablesorter table-responsive" id="alerts">
        <thead>
            <tr>
                <th class="header">ID</th>
                <th class="header">Archive</th>
            </tr>
        </thead>
        <tbody>
        @foreach($alert->alerts as $alert)
            <tr>
                {{ Form::open(array('route' => array('archive', $alert->id), 'role'=>'form')) }}
                <td><button type="submit" class="btn btn-warning" name="archive">Archive</button></td>
                {{ Form::close() }}
            </tr>
        @endforeach
    </tbody>
    </table>
    

    【讨论】:

    • 嗨 Jono20201,不幸的是,这不适用于 forloop 内的多个结果,它返回最后一个 $alert-&gt;id
    • @Svengali 用替代方法更新了答案。
    • 您好 Jono20201,不幸的是,您修改后的答案仍然只引用结果中的最后一个警报 ID。无论我点击哪个存档按钮,它始终是提交的最后一个 ID。
    • @Svengali 请发布您的循环代码。我认为问题在于循环,因为我发布的代码不仅仅引用循环是正确的。
    • @Svengali 很高兴我们可以为您解决问题! :)
    猜你喜欢
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 2018-08-20
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    相关资源
    最近更新 更多