WellNo WellNo - 1 year ago 264
PHP Question

Laravel - delete multiple data from pivot-table with checkbox

I'm trying to make a tag-delete that works with checkboxes. Imagine the user have about 10 products and every product have 3 different tags.

Currently the user only can delete a single tag. After every tag-delete the page refreshes and he can delete another tag. this isn't really user-friendly. That's why I'm trying to do a multiple selection for tags and delete all the selected tags at one button-click.

That's how it looks right now:

{!! Form::open(['action' => 'ProductController@detach', 'method' => 'post']) !!}
<div class="container">
<div class="table-responsive">
@foreach($products as $product)
<td>{{ $product->name }}</td>
@foreach($product->tags as $tag)
{!! Form::hidden('tag_id', $tag->id) !!}
<input type="checkbox" name="xxxxx" value="{{ xxxx }}"><br>

{!! Form::button('Delete') !!}
{!! Form::close() !!}

My problem is that I need the product_id + tag_id to detach them.

If I'm pressing the delete button, I'm getting this data passed to my controller:


The main problem is, that my program just gives me the very last product_id. No matter if I haven't selected any tag from this product. It always gives me this product_id. I also need something like a multiple array passed to my controller to work with.

Something like this would be perfect:

[0] = product_id = 1
tag_id = 50,60,80
[1] = product_id = 2
tag_id = 11,22,33

My reply to your answer:

I'm sorry for my late answer..

I've tried it and it works nearly perfect. Only problem is that if two different products have the same tag, my programm will only return the last product with his tag. for example:

product_id 1 and product_id 2 have tag_id 3.

As an output I need: product_id1 : tag_id 3, product_id2 : tag_id 3

But I only get the last product_id with the tag passed, all other products with the same tag_id are ignored. So I'm just getting this as a result:

product_id2 : tag_id3.

I hope you understand what I'm trying to say.. my english isn't the best..

Answer Source

You can pass the checkbox as an array field like this, with key as tag id and value is the product id,

@foreach($product->tags as $tag)
 <input type="checkbox" name="tagtodelete[{{ $tag->id.'-'.$product->id }}]" value="{{ $product->id }}"><br>

and in your controller you can get the value as an array ,

$tagsleftoffs = (array) $request->input('tagtodelete');
foreach($tagsleftoffs as $tagId => $productId){
//perform your action here
$productId = explode('-',$tagId);
echo $productId[0] ; //is tag Id
echo $productId[1] ; //is product Id