When dealing with dynamic data sources, especially from databases, some columns may contain sensitive or irrelevant information. For example:
- A user table might contain a
password
column that should not be displayed. - A product table may have internal
inventory_id
orsupplier_notes
that are unnecessary for users.
To solve this, we can create a middleware that removes specific columns before rendering.
Create a RemoveColumnsMiddleware
The
iterateTrsIn()
method simplifies iterating through rows, while thegetCellCollection()
allows us to remove unwanted columns efficiently.
use Ucscode\HtmlComponent\TableGenerator\TableGenerator;
use Ucscode\HtmlComponent\TableGenerator\Abstraction\AbstractMiddleware;
use Ucscode\HtmlComponent\TableGenerator\Component\Section\Tr;
use Ucscode\HtmlComponent\TableGenerator\Contracts\TableSegmentInterface;
class RemoveColumnsMiddleware extends AbstractMiddleware
{
public function process(Table $table): void
{
// Loop through each cell in the table
$this->iterateCellsIn($table, function (CellInterface $cell, Tr $tr) {
// Remove cells whose meta "columnName" matches unwanted columns
if ($cell->getMeta()->get('columnName') === 'password') {
$tr->getCellCollection()->remove($cell);
}
});
}
}
Use the RemoveColumnsMiddleware
on the TableGenerator
// Load data (assuming $adapter fetches user or product data)
$tableGenerator = new TableGenerator($adapter, new RemoveColumnsMiddleware());
// Render the table
echo $tableGenerator->render();
Expected Output
If the original data contained a password
column, it will now be removed from the rendered table.
Before Removing Columns
ID | Name | Password | |
---|---|---|---|
1 | John | john@example.com | abc123 |
2 | Jane | jane@example.com | pass456 |
After Applying RemoveColumnsMiddleware
ID | Name | |
---|---|---|
1 | John | john@example.com |
2 | Jane | jane@example.com |