eaglehdr's avatar

Getting extra checkbox while rendering Livewire component

I have a MSSQL database, where I will have a lot of products data. I have to list products on the basis of a column name GroupID. products are from different sources, so each source has an id ( sourceID ) so if 2 sources have same products, there are two rows of that product in the table ( don't ask me why, I cannot change DB, I am only allowed to read it and list the products. so let say my tables is

| ProductID | GroupID  | SourceID | Snmbr |  
|-----------|----------|----------|-------|
| T701-1    | TVSTND   | 41       | 11    | 
| T701-1    | TVSTND   | 22       | 10    |
| T287-9    | TVSTND   | 22       | 13    |

I am using limit and offset for pagination

$spProducts = DB::table($this->prdTable)
                    ->select('*')
                    ->whereIn('GroupID', $this->grpID)
                    ->offset($startIndex)
                    ->limit($itemsPerPage)
                    ->get();

startindex is set from livewire variable and itmesperpage remains same (for now). The issue is when render the table (html table) using loop. I am rendering a checkbox containing product id. the table row shows two checkboxes for each T701-1 product row. screenshot

I tried to print loop variable to see if it is squeezing two rows in one. but unable to see why it is showing checkbox for same product twice in a single row

0 likes
3 replies
LaryAI's avatar
Level 58

The issue is occurring because the Livewire component is rendering two rows for the same product. One solution is to group the products by their ProductID and then loop through the groups to render the table rows. Here's an example code snippet:

$spProducts = DB::table($this->prdTable)
                ->select('*')
                ->whereIn('GroupID', $this->grpID)
                ->offset($startIndex)
                ->limit($itemsPerPage)
                ->get();

$productGroups = $spProducts->groupBy('ProductID');

foreach ($productGroups as $productId => $products) {
    <tr>
        <td><input type="checkbox" value="{{ $productId }}"></td>
        <td>{{ $productId }}</td>
        <td>{{ $products[0]->GroupID }}</td>
        <td>{{ $products[0]->Snmbr }}</td>
    </tr>
}

In this example, we first group the products by their ProductID using the groupBy method. Then, we loop through each group and render a table row with a single checkbox for the product and the other relevant information. Since each group represents a unique product, we only render one checkbox per product.

Snapey's avatar

perhaps if you showed the blade file?

eaglehdr's avatar

Ah! dumb me.. I was rendering checkbox IDs with $productID . while product IDs were multiple. I had to changed it to a unique id, so I changed it to $loop->index

Please or to participate in this conversation.