简体   繁体   中英

Trying to delete multiple records at once in Laravel

I'm trying to make table with checkboxes where admin can check multiple products and delete them. So far I've made the form

@foreach($products as $product)
    {{ Form::open() }}
          <input type="checkbox" name="delete[]" value="{{ $product->product_id }}">
          <a class="btn btn-primary" href="{{ URL::to('/admin/products/multiDdelete') }}?_token={{ csrf_token() }}">Delete</a>
    {{ Form::close() }}
@endforeach

This is in my route

Route::get ('/admin/products/multiDdelete', ['uses' => 'AdminController@testDelete', 'before' => 'csrf|admin']);

And this in the controller

public function testDelete() {

    $delete = Input::only('delete')['delete'];

    $pDel = Product::where('product_id', $delete);

    $pDel->delete();
    return Redirect::to('/admin/test')->with('message', 'Product(s) deleted.');
} 

So far when I check products and hit Delete page reload and I get Product(s) deleted but products aren't deleted. I think the problem is in how I pass ID's .. but I can't figured it out.

Your query isn't returning anything useful here. Even with ->get() , it would return a collection, which you can't use the way you want. You can add delete to your query instead:

Product::whereIn('product_id', $delete)->delete();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM