Skip to content

Component Columns โ€‹

This section covers the PowerGrid Table Component Column setup.

Here you will find:

Introduction โ€‹

With your Component's Data Source Fields properly configured, you can start to configure which columns will be displayed in your Table Component.

If you have already added Columns to your Table, visit the section Column Features to learn more about Table Columns.

Include Columns โ€‹

PowerGrid offers two ways to add columns. Let's explore them in this subsection.

Columns are added inside the array in the method columns().

Add Column โ€‹

To show a column, add a new array item Column::add().

You should always provide both methods title() and field(), to give your column a title and link it to a data source field.

Then, you may chain other Column Configuration Methods to set up your column.

Example:

php
// app/Livewire/DishTable.php

use PowerComponents\LivewirePowerGrid\Facades\PowerGrid;
use PowerComponents\LivewirePowerGrid\PowerGridComponent;
use PowerComponents\LivewirePowerGrid\Column;

class DishTable extends PowerGridComponent
{
    public function columns(): array
    {
        return [
            Column::add()
                ->title('ID')
                ->field('id'),

            Column::add()
                ->title('Dish name')
                ->field('name'),

            Column::add()
                ->title('Price')
                ->field('price'),

            Column::add()
                ->title('Discount Price')
                ->field('price_with_discount', 'price'),
        ];
    }
}

Make Column โ€‹

In addition to Column::add(), PowerGrid offers a shorter way to make a column.

To show a column, add a new Column::make() array item. You must provide two parameters: $title and $field. This will give your column a title and link it to a data source field.

Then, you may chain other Column Configuration Methods to set up your column.

Example:

php
// app/Livewire/DishTable.php

use PowerComponents\LivewirePowerGrid\Facades\PowerGrid;
use PowerComponents\LivewirePowerGrid\PowerGridComponent;
use PowerComponents\LivewirePowerGrid\Column;

class DishTable extends PowerGridComponent
{
    public function columns(): array
    {
        return [
            Column::make(title: 'ID', field: 'id'),

            Column::make(title: 'Dish name', field: 'name'),

            Column::make(title: 'Price', field: 'price'),

            Column::make(
                    title: 'Discount Price', 
                    field: 'price_with_discount', 
                    dataField: 'price'
            )
        ];
    }
}

๐ŸŽ‰ Ok, all done!

Let's explore the various Configuration Options available in our Component.

Column Data Field โ€‹

When using Data source Custom Fields or Table joins, you must pass the $dataField parameter, indicating where the "original" data can be found in the database. This allows data search, filtering and column sorting.

The $dataField is available for Column::add() and Column::make() methods.

In the next example, the column "Dish Uppercase" will retrieve data from the Custom Field name_uppercase.

Since this field does not exist in the database, we indicate the data field name in the Table dishes to be used for data search, filtering and column sorting.

php
// app/Livewire/DishTable.php

use PowerComponents\LivewirePowerGrid\Column;

public function columns(): array
{
    return [
        Column::make(
                title: 'Dish Uppercase', 
                field: 'name_uppercase', 
                dataField: 'dishes.name'
            )
            ->searchable(),
    ];
}

The next example retrieves the Custom Field category_name from the join relationship and indicates the field name in the categories Table for data search and filtering.

php
// app/Livewire/DishTable.php

use PowerComponents\LivewirePowerGrid\Column;

public function columns(): array
{
    return [
        Column::add()
            ->title('Category Name')
            ->field(field: 'category_name', dataField: 'categories.name'),
    ];
}

Column Configuration Methods โ€‹

The methods below can be chained to the PowerComponents\LivewirePowerGrid\Column class.

TIP

You can also create custom methods using macro.

title() โ€‹

Set the column title (displayed in the column header).

Parameters
(string) $title

Example:

php
use PowerComponents\LivewirePowerGrid\Column;

Column::add()
    ->title('Dish Price'),

You may also pass HTML code to be rendered as title.

This might be helpful when using a Font Icon package, such as Font Awesome.

php
 Column::add()
    ->title('<i class="fas fa-low-vision" title="Visibility"></i>')

Notice of Non-Affiliation: Livewire PowerGrid is not in any way associated with the Font Awesome.


field() โ€‹

Links the column to an existing data source field.

ParameterDescription
(string) $field(string) data source field
(string) $dataField(string) database name and field (dot notation) [OPTIONAL]

Example:

php
use PowerComponents\LivewirePowerGrid\Column;

Column::add()
    ->field('name'),

The next example uses $dataField to indicate the database Table and field in data source using table joins.

php
use PowerComponents\LivewirePowerGrid\Column;

Column::add()
    ->field('name', 'dishes.name'),

Column::add()
    ->field('category_name', 'categories.name'),

placeholder() โ€‹

Sets a placeholder for the Filter input text.

Parameter
(string) $placeholder

Example:

php
use PowerComponents\LivewirePowerGrid\Column;

Column::make('Dish name', 'name')
    ->placeholder('Enter the name'),

searchable() โ€‹

Allow/include column to be searched with the Search Input.

Read more about Searching Data.

Example:

php
use PowerComponents\LivewirePowerGrid\Column;

Column::make('Dish name', 'name')
    ->searchable(),

Column::make('category_name', 'categories.name'),
    ->searchable(),

๐Ÿ“ NOTE

You must pass the $dataField parameter for the search to work with Custom Fields and join relationships.


searchableRaw() โ€‹

Sometimes, you may need to use RAW SQL to search data.

The next example illustrates a case where allowing to filter by date as "d/m/Y".

php
    Column::make('Production date', 'produced_at_formatted', 'produced_at')
        ->searchableRaw('DATE_FORMAT(dishes.produced_at, "%d/%m/%Y") like ?'), 

๐Ÿš€ See it in action

See an interactive example using searchableRaw().

sortable() โ€‹

Adds the sort control button to the column header.

Read more about Sorting Data.

Example:

php
use PowerComponents\LivewirePowerGrid\Column;

Column::make('Dish name', 'name')
    ->sortable(),

Column::make('category_name', 'categories.name'),
    ->sortable(),

๐Ÿ“ NOTE

You must pass the $dataField parameter for the sorting to work with Custom Fields and join relationships.


fixedOnResponsive() โ€‹

Fix the column when in a Responsive Table.

Example:

php
use PowerComponents\LivewirePowerGrid\Column;

Column::make('Dish name', 'name')
    ->fixedOnResponsive(),

index() โ€‹

Displays a column with the row index value.

Example:

php
use PowerComponents\LivewirePowerGrid\Column;

Column::make('Dish name', 'name')
    ->index(),

hidden() โ€‹

Hides the column in your PowerGrid Table view.

ParameterDescription
(bool) $isHiddenWhen true, it hides the column from the Table view but not from the Hide/Show toggle button
(bool) $isForceHiddenWhen true, it removes the column from the Hide/Show toggle button

The example below hides the column "Dish Name" from the Table view, however the end user can still enable its visibility in the "Hide/Show" toggle.

php
use PowerComponents\LivewirePowerGrid\Column;

Column::make('Dish name', 'name')
    ->hidden(isHidden: true, isForceHidden: false),

The next example hides the column "Dish Name" from the Table view and also removes the option to change its visibility in the "Hide/Show" toggle, so the user cannot make the column visible again.

php
use PowerComponents\LivewirePowerGrid\Column;

Column::make('Dish name', 'name')
    ->hidden(isHidden: true, isForceHidden: true),

๐Ÿš€ See it in action

See an interactive example using hidden().


visibleInExport() โ€‹

Sometimes, you may want to hide and exclude a specific column when Exporting Data. This method gives you control whether the column will be included or not in the file containing the exported data.

ParameterDescription
(bool) $visibleWhen false, the column when be removed from the data export file.

Example:

php
use PowerComponents\LivewirePowerGrid\Column;

Column::make('Dish price', 'price')
    ->hidden()
    ->visibleInExport(false), // will not include in exported file

๐Ÿš€ See it in action

See an interactive example using visibleInExport().


headerAttribute() โ€‹

Adds the given class or style to the column header.

ParameterDescription
(string) $classAttrHTML class
(string) $styleAttrHTML style

Example:

php
use PowerComponents\LivewirePowerGrid\Column;

Column::make('Dish name', 'name')
    ->headerAttribute('text-center', 'color:red')

bodyAttribute() โ€‹

Adds the given class or style to every Table row in this column.

ParameterDescription
(string) $classAttrHTML class
(string) $styleAttrHTML style

Example:

php
use PowerComponents\LivewirePowerGrid\Column;

Column::make('Dish name', 'name')
    ->bodyAttribute('text-center', 'color:red')

contentClassField() โ€‹

Adds the content from the specified data source field to every row's <span class=""></span>.

ParameterDescription
(string) $dataField(string) data source field

Example:

php
use PowerComponents\LivewirePowerGrid\Column;

Column::make('Dish name', 'name')
    ->contentClassField('status_class')

contentClasses() โ€‹

Add a CSS class wrapping the cell content in a <span class=""></span> tag.

When passing an array, PowerGrid will match the key against the column content and apply the corresponding CSS class.

ParameterDescription
(array,string) $contentClassesColumn content => CSS Class assignments

Example:

php
Column::make('Dish name', 'name')
    ->contentClasses('text-blue-600');

Column::make('Dish Availability', 'availability')
    ->contentClasses([
          'available'    => 'text-green-600',
          'out-of-stock' => 'text-red-600'
     ]);

template โ€‹

If you want to customize a record in the table without using Blade's processing, you can use the rowTemplate() method. This approach prevents the unnecessary creation of Blade components for the same field across different rows by leveraging JavaScript instead.

Consider the following example:

INFO

For each rendered row in the 'name' field, a view will be created in PHP during the rendering process:

php
public function fields(): PowerGridFields
{
    return PowerGrid::fields()
        ->add('id')
        ->add('name', function ($row) {
            return \Blade::render(<<<blade
                <div id="custom-\$id" class="bg-red-100 py-1 rounded px-3">\$name</div>
            blade, [
                'id'   => $row->id,
                'name' => $row->name,
            ]);
        })
}

We can simplify this by using JavaScript to handle the rendering, as shown below:

php
 public function fields(): PowerGridFields
{
    return PowerGrid::fields()
        ->add('id')
        ->add('name', function ($row) {
            return [ 
                'template-name' => [ 
                    'id'   => $row->id, 
                    'name' => $row->name, 
                ], 
            ];
        });
}

public function columns(): array
{
    return [
        Column::make('ID', 'id')
            ->searchable()
            ->sortable(),

        Column::make('Name', 'name')
            ->template() 
            ->searchable()
            ->sortable(),
    ];
}
    
public function rowTemplates(): array
{ 
    return [ 
        'template-name' => '<div id="custom-{{ id }}" class="bg-red-100 py-1 rounded px-3">{{ name }}</div>', 
    ]; 
} 

In this setup, we instruct PowerGrid to look for 'template-name' and replace the HTML with the corresponding template during rendering. By doing so, the layout and styling are managed by JavaScript, which dynamically populates the fields with the appropriate data for each row.

This approach reduces the overhead associated with generating Blade views for each row, leading to improved performance and easier maintenance, especially when dealing with large datasets. Instead of repeatedly rendering Blade components, the JavaScript-based solution efficiently handles the customization directly in the browser, making your application more responsive and streamlined.

Custom Macros โ€‹

  • If you need to add different query logic when searching for example, you can create a new macro (let's assume searchableDateFormat):

AppServiceProvider, boot method.

php
Column::macro('searchableDateFormat', function () {
      $this->rawQueries[] = [
          'method'   => 'orWhereRaw',
          'sql'      => 'DATE_FORMAT('.$this->dataField.', "%d/%m/%Y") like ?',
          'bindings' => ['%{search}%'],
          'enabled'  => function (PowerGridComponent $component) {
              return filled($component->search);
          },
      ];

      return $this;
});

Now, in any PowerGrid table component:

php
 Column::make('Created At', 'created_at')
     ->searchableDateFormat(),
KeyDescription
methodThe method used to add a raw query to the query builder, in this case, orWhereRaw.
sqlThe SQL query that will be executed. It performs a case-insensitive search on the specified column of the table.
bindingsAn array containing a closure that processes the search term by converting it to lowercase and wrapping it with wildcard characters (%). The processed search term is bound to the query.
enabledA closure that determines whether the search should be applied, based on whether the search term is filled (filled).

Created By Luan Freitas and @DanSysAnalyst