Hide/Show Columns in Table using Livewire

In this Tutorial, we will see how we can allow User to change the visibility of Columns in a Table using Livewire. This is the part 2 of the Series. In Part 1 of the Series we saw how to generate Pagination Dropdown.

We will show User the checkboxes with list of all Columns in the Table. Columns will then show or hide as soon as the User check the checkboxes. Here is how the preview of the functionality.

I would assume that you already have a working Livewire Component which is showing the Records in a Table Form. First of all we are going to add a New Property $columns to our Livewire Component. We would also initialize this will all the Columns in our Table as follows:

public $columns = ['Id','Name','Price','Sku','Status','Created At','Updated At'];

We will also add another property $selectedColumns and this would contain all the columns that User has selected to display in the HTML Table.

public $selectedColumns = [];

We have defined it as an empty array. However, in the mount method we would set its value same as $columns which means that initially all the columns would be displayed to the User.

    public function mount()
    {
        $this->selectedColumns = $this->columns;
    }

Now in the View, we would loop through the $columns so that User can select the columns and we would wire:model it to $selectedColumns

@foreach($columns as $column)
    <input type="checkbox" wire:model="selectedColumns" value="{{$column}}">
    <label>{{$column}}</label>
@endforeach

So anytime User uncheck a checkbox, corresponding value will be removed from the $selectedColumns array. And if a User checks a checkbox, value will be added to the $selectedColumns array.

Since we initialized the $selectedColumns in the mount method, all the Columns would be checked by default.

And now finally we can wrap all the td using the following if Condition.

@if(in_array('Price', $selectedColumns))
<td>Price</td>
@endif

So in the above example, the Price Column would only show if it exists in the $selectedColumns. Similarly we need to wrap the other td using the same if Condition. Do not forget to wrap both the Heading as well as the Body of the Table.

We can slightly improve the code by creating the following method in our Component.

    public function showColumn($column)
    {
        return in_array($column, $this->selectedColumns);
    }

And then instead of the if Condition in the View, we can call the showColumn method like below

@if($this->showColumn('Price'))
<td>Price</td>
@endif

At this stage, Users will have the ability to Show/Hide Column and you will have a working example similar to the image shared at the start of the tutorial.

If you are interested, please checkout the Livewire Package tall-crud-generator which automatically generates all the Code related to Show/Hide Columns that we discussed in this tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *