Laravel多次删除

时间:2018-05-04 03:32:08

标签: php laravel

我尝试将多个选择添加到我的应用中并立即删除数据,但它们不会从数据库中删除。

controller

public function multipledel(Request $request){
  $deli = $request->input('productsfordel');
  $product = Product::whereIn('id', $deli);
  $product->delete();
  return redirect()->route('products.index')->with('success', 'Selected products are successfully deleted.');
}

route

  Route::post('delmultipleproducts', 'ProductController@multipledel')->name('delmultipleproducts');

blade

//multiple delete form starts before table begin
{!! Form::open(['method' => 'Post', 'route' => ['delmultipleproducts'] ]) !!}

//delete button
<button name="bulk_delete" id="bulk_delete" data-toggle="tooltip" data-placement="top" title="Delete Selected" class="btn btn-xs btn-theme04" type="submit"><i class="fa fa-trash-o"></i></button>   

<thead>
//table headears
</thead>
<tbody>
@foreach($products as $product)
<tr>
  //my checkbox's
  <td>
    <input type="checkbox" name="productsfordel[]" class="checkboxes" value="{{ $product->id }}" />
  </td>

// my multiple delete form closes here
{!! Form::close() !!}

//rest of the table...

问题

  1. 我收到了几种错误!
  2. 首先

      

    为foreach()提供的参数无效

    第二

      

    SQLSTATE [23000]:完整性约束违规:1451无法删除或   更新父行:外键约束失败

    第三

    它返回我的成功会话并说Selected products are successfully deleted.,但他们不是。

    看来

    我认为我得到的错误是指我的产品附加数据,我在普通删除方法one by one

    中有下面的代码
    public function destroy($id)
        {
          $product = Product::findOrFail($id);
          $product->suboptions()->detach();
          $product->subspecifications()->detach();
          if(!empty($product->imageOne)){
            Storage::delete($product->imageOne);
          }
          if(!empty($product->imageTwo)){
            Storage::delete($product->imageTwo);
          }
          $product->delete();
          return redirect()->route('products.index')->with('success','Product successfully deleted');
        }
    

    正如你所看到的,我有几个条件和同步数据到我的每个产品但是在我的多重删除方法中我没有它们,但是我也尝试包含它们但是它给了我{{1的错误我不确定是否需要以某种方式对$product = Product::whereIn('id', $deli);进行排列?

    任何想法?

    更新

    我意识到当我尝试$deli时,我的控制器没有任何内容会发送,而是选择了dd($deli);id

2 个答案:

答案 0 :(得分:0)

Eloquent whereIn确实要求您传递一系列值,这就是您收到foreach通知的原因。

  

SQLSTATE [23000]:完整性约束违规:1451无法删除或更新父行:外键约束失败

你得到这个,只是因为你的外键没有ON DELETE行为,所以你应该首先手动删除子(引用)记录(模型)。

答案 1 :(得分:0)

当涉及多次删除时,您可以简单地执行

Product::destroy($request->get('productsfordel'));
return redirect()->route('products.index')->with('success', 'Selected products are successfully deleted.');