Skip to content

Add Columns / Fields ​

Before adding columns to your table, you must make Datasource fields available as columns.

Adding Fields ​

To include fields from your datasource, you should start inside the fields() method inside your component.

First, call the PowerGrid::fields() and chain as many datasource fields as you need.

If you need to format your data, you may pass a Closure as the second parameter to interact with data coming from the data source.

The next example creates 4 columns:

  • id: based on the id field.
  • name: based on the name field.
  • name_uppercase: returns the name field value transformed to UPPER CASE.
  • price_after_taxes: returns the price value with taxes. This example uses a fictitious tax calculator class.
php

use PowerComponents\LivewirePowerGrid\PowerGrid;
use PowerComponents\LivewirePowerGrid\PowerGridFields;

public function fields(): PowerGridFields
{
    return PowerGrid::fields()
    ->add('id')
    ->add('name')
    ->add('name_uppercase', function (Dish $model) {
        return strtoupper($model->name);
    })
    ->add('price_after_taxes', function (Dish $model) {
        return taxCalculator::vat($model->price, 'PT');
    });
}

    //...

use PowerComponents\LivewirePowerGrid\PowerGrid;
use PowerComponents\LivewirePowerGrid\PowerGridFields;

public function fields(): PowerGridFields
{
    return PowerGrid::fields()
    ->add('id')
    ->add('name')
    ->add('name_uppercase', function (Dish $model) {
        return strtoupper($model->name);
    })
    ->add('price_after_taxes', function (Dish $model) {
        return taxCalculator::vat($model->price, 'PT');
    });
}

    //...

addColumns (Deprecated) ​

The addColumns() is deprecated and will be removed in PowerGrid 6.0.

It works similarly to the PowerGrid::fields() as demonstrated by the example below.

php
use PowerComponents\LivewirePowerGrid\PowerGrid;
use PowerComponents\LivewirePowerGrid\PowerGridColumns;

public function addColumns(): PowerGridColumns
{
    return PowerGrid::columns()
        ->addColumn('id')
        ->addColumn('name')
        ->addColumn('name_uppercase', function (Dish $model) {
          return strtoupper($model->name);
        })
        ->addColumn('price_after_taxes', function (Dish $model) {
          return taxCalculator::vat($model->price, 'PT');
        });
}
use PowerComponents\LivewirePowerGrid\PowerGrid;
use PowerComponents\LivewirePowerGrid\PowerGridColumns;

public function addColumns(): PowerGridColumns
{
    return PowerGrid::columns()
        ->addColumn('id')
        ->addColumn('name')
        ->addColumn('name_uppercase', function (Dish $model) {
          return strtoupper($model->name);
        })
        ->addColumn('price_after_taxes', function (Dish $model) {
          return taxCalculator::vat($model->price, 'PT');
        });
}

Sortable ​

WARNING

Whenever the column name is different from the one in the database, remember to reference it in dataField in the Column::field() method otherwise sortable will not work.

php
//..
<!-- 🚫 Wrong -->
public function addColumns(): PowerGridColumns
{
    return PowerGrid::columns()
         ->addColumn('created_at', function (Dish $dish) {
            return Carbon::parse($dish->created_at)->format('d/m/Y H:i');
         })
}

public function columns(): array
{
   return [
      Column::add()
         ->title('Created At')
         ->field('created_at') 🚫
         ->searchable()
         ->sortable()
   ]   
}
//..
<!-- 🚫 Wrong -->
public function addColumns(): PowerGridColumns
{
    return PowerGrid::columns()
         ->addColumn('created_at', function (Dish $dish) {
            return Carbon::parse($dish->created_at)->format('d/m/Y H:i');
         })
}

public function columns(): array
{
   return [
      Column::add()
         ->title('Created At')
         ->field('created_at') 🚫
         ->searchable()
         ->sortable()
   ]   
}
php
//..
<!-- βœ… Right -->
public function addColumns(): PowerGridColumns
{
  return PowerGrid::columns()
     ->addColumn('created_at_formatted', function (Dish $dish) {
        return Carbon::parse($dish->created_at)->format('d/m/Y H:i');
     })
}

public function columns(): array
{
    return [
        Column::add()
           ->title('CREATED AT')
           ->field('created_at_formatted', 'created_at') βœ…
           ->searchable()
           ->sortable(),
    ]
}
//..
<!-- βœ… Right -->
public function addColumns(): PowerGridColumns
{
  return PowerGrid::columns()
     ->addColumn('created_at_formatted', function (Dish $dish) {
        return Carbon::parse($dish->created_at)->format('d/m/Y H:i');
     })
}

public function columns(): array
{
    return [
        Column::add()
           ->title('CREATED AT')
           ->field('created_at_formatted', 'created_at') βœ…
           ->searchable()
           ->sortable(),
    ]
}

Searchable ​

WARNING

Always add the actual column name in the database if it is searchable.


php
//..
<!-- 🚫 Wrong -->
public function addColumns(): PowerGridColumns
{
    return PowerGrid::columns()
        ->addColumn('price_formatted', function (Dish $dish) {
            return $fmt->formatCurrency($dish->price, "EUR");
        })
}

public function columns(): array
{
    return [
        Column::add()
           ->title('Price')
           ->field('price_formatted', 'price') 
           ->searchable()
           ->sortable(),
    ];
}
//..
<!-- 🚫 Wrong -->
public function addColumns(): PowerGridColumns
{
    return PowerGrid::columns()
        ->addColumn('price_formatted', function (Dish $dish) {
            return $fmt->formatCurrency($dish->price, "EUR");
        })
}

public function columns(): array
{
    return [
        Column::add()
           ->title('Price')
           ->field('price_formatted', 'price') 
           ->searchable()
           ->sortable(),
    ];
}
php
//..
<!-- βœ… Right -->
public function addColumns(): PowerGridColumns
{
  return PowerGrid::columns()
        ->addColumn('price')
        ->addColumn('price_formatted', function (Dish $dish) {
            return $fmt->formatCurrency($dish->price, "EUR");
        })
}

public function columns(): array
{
    return [
        Column::add()
           ->title('Price')
           ->field('price_formatted', 'price') βœ…
           ->searchable()
           ->sortable(),
    ];
}
//..
<!-- βœ… Right -->
public function addColumns(): PowerGridColumns
{
  return PowerGrid::columns()
        ->addColumn('price')
        ->addColumn('price_formatted', function (Dish $dish) {
            return $fmt->formatCurrency($dish->price, "EUR");
        })
}

public function columns(): array
{
    return [
        Column::add()
           ->title('Price')
           ->field('price_formatted', 'price') βœ…
           ->searchable()
           ->sortable(),
    ];
}

beforeSearch can be run if you want to change the behavior of the β€˜search’ property before performing the search within the PowerGrid. This is useful when we have to deal with the query before querying the database.

For example, we have a phone field without a mask in the database, but the user types the search with a mask. With this PR you can process before removing the characters that do not need to be sent in the query

php

public function columns()
{
    return [
        Column::make('Phone', 'phone_editable', 'phone')
            ->searchable(),
    ];
}

public function beforeSearchPhone($search): string
{
    return str($search)->replaceMatches('/[^0-9]+/', '')->toString();
}

public function beforeSearch(string $field = null, string $search = null)
{
    if ($field === 'phone') {
         return str($search)->replaceMatches('/[^0-9]+/', '')->toString();
    }

    return $search;
}

public function columns()
{
    return [
        Column::make('Phone', 'phone_editable', 'phone')
            ->searchable(),
    ];
}

public function beforeSearchPhone($search): string
{
    return str($search)->replaceMatches('/[^0-9]+/', '')->toString();
}

public function beforeSearch(string $field = null, string $search = null)
{
    if ($field === 'phone') {
         return str($search)->replaceMatches('/[^0-9]+/', '')->toString();
    }

    return $search;
}

Closure Examples ​

Sometimes, you need to display data in a human-friendly way.

This is often the case with date, currency and boolean values.

Let's check some examples using closures to format data!

WARNING

When using closures to output user defined values directly to HTML, you should escape user defined values using Laravel's e helper to prevent XSS attacks.

You can use closures to render HTML inside table cells.

The example below creates a new column called location_link containing a link formed by the lat_long field and the location_name field.

php
//..
public function addColumns(): PowerGridColumns
{
    return PowerGrid::columns()
        ->addColumn('location_link', function (Dish $model) {
            return '<a href="https://www.google.com/maps/search/' . e($model->lat_long) . '">'. e($model->location_name) .'</a>'; 
        });
}
//..
public function addColumns(): PowerGridColumns
{
    return PowerGrid::columns()
        ->addColumn('location_link', function (Dish $model) {
            return '<a href="https://www.google.com/maps/search/' . e($model->lat_long) . '">'. e($model->location_name) .'</a>'; 
        });
}

The example above produces the HTML <a href="https://www.google.com/maps/search/-22.973587702676607,-43.18527287193542">Copacabana</a> which would look like: Copacabana.

WARNING

When using closures to output user defined values directly to HTML, you should escape user defined values using Laravel's e helper to prevent XSS attacks.


Date ​

The database field created_at has date stored as yyyy-mm-dd H:i:s 2021-01-20 10:05:44.

The following code demonstrates a new custom column created_at_formatted.

In this column, date is parsed and displayed as d/m/Y H:i (20/01/2021 10:05).

php
//..
public function addColumns(): PowerGridColumns
{
    return PowerGrid::columns()
        ->addColumn('created_at_formatted', function (Dish $model) {
            return Carbon::parse($model->created_at)->format('d/m/Y H:i');
        });
}
//..
public function addColumns(): PowerGridColumns
{
    return PowerGrid::columns()
        ->addColumn('created_at_formatted', function (Dish $model) {
            return Carbon::parse($model->created_at)->format('d/m/Y H:i');
        });
}

Currency ​

The next example creates a new custom column called price_in_eur.

This custom column displays the price amount (170.90) formatted as Portuguese Euro (170,90 €):

php
//..
public function addColumns(): PowerGridColumns
{
  $fmt = new NumberFormatter('pt_PT', NumberFormatter::CURRENCY);

  return PowerGrid::columns()
        ->addColumn('price_in_eur', function (Dish $model) {
            return $fmt->formatCurrency($model->price, "EUR");
        });
}
//..
public function addColumns(): PowerGridColumns
{
  $fmt = new NumberFormatter('pt_PT', NumberFormatter::CURRENCY);

  return PowerGrid::columns()
        ->addColumn('price_in_eur', function (Dish $model) {
            return $fmt->formatCurrency($model->price, "EUR");
        });
}

Text summary ​

Large amounts of text can compromise the readability of your table. This is often the case with a product description, list of items, or blog posts.

It is a common practice to display an introduction of your text, an excerpt containing a certain number of words, instead of the full content.

This example shows how to trim the full text in the $dish->description database field:

text
Homemade Lasagna with our slow-cooked beef ragΓΉ, traditional bechamel and parmesan. 
Lasagna is comfort food and it's always good when prepared correctly.
Homemade Lasagna with our slow-cooked beef ragΓΉ, traditional bechamel and parmesan. 
Lasagna is comfort food and it's always good when prepared correctly.

Into a new column named description_excerpt:

text
"Homemade Lasagna with our slow-cooked beef ragΓΉ, traditional..."
"Homemade Lasagna with our slow-cooked beef ragΓΉ, traditional..."

Code:

php
<?php

use Illuminate\Support\Str;

public function addColumns(): PowerGridColumns
{
    return PowerGrid::columns()
       ->addColumn('description_excerpt', function (Dish $model) {
           return Str::words(e($model->description), 8); //Gets the first 8 words
       });
}
<?php

use Illuminate\Support\Str;

public function addColumns(): PowerGridColumns
{
    return PowerGrid::columns()
       ->addColumn('description_excerpt', function (Dish $model) {
           return Str::words(e($model->description), 8); //Gets the first 8 words
       });
}

WARNING

When using closures to output user defined values directly to HTML, you should escape user defined values using Laravel's e helper to prevent XSS attacks.

Boolean ​

True/false is not friendly for the end user. Displaying "Yes/No" is a better alternative.

In this example, we have a new custom column available which displays "yes"/"no" based on the database field in_stock (true/false).

php
//..
public function addColumns(): PowerGridColumns
{

  return PowerGrid::columns()
        ->addColumn('available', function (Dish $model) {
            return ($model->in_stock ? 'yes' : 'no');
        });
}
//..
public function addColumns(): PowerGridColumns
{

  return PowerGrid::columns()
        ->addColumn('available', function (Dish $model) {
            return ($model->in_stock ? 'yes' : 'no');
        });
}

Enum ​

If you have an Enum with labels, you can use a closure to display label values instead of default case values.

Available only in Php 8.1+.

php
<?php

enum Diet: int
{
    case ALL      = 0;
    case VEGAN    = 1;
    case CELIAC   = 2;

    public function labels(): string
    {
        return match ($this) {
            self::ALL         => "🍽️ All diets",
            self::VEGAN       => "🌱 Suitable for Vegans",
            self::CELIAC      => "πŸ₯œ Suitable for Celiacs",
        };
    }
}
<?php

enum Diet: int
{
    case ALL      = 0;
    case VEGAN    = 1;
    case CELIAC   = 2;

    public function labels(): string
    {
        return match ($this) {
            self::ALL         => "🍽️ All diets",
            self::VEGAN       => "🌱 Suitable for Vegans",
            self::CELIAC      => "πŸ₯œ Suitable for Celiacs",
        };
    }
}

The following example makes your table rows show 🍽️ All diets instead of the database value 0.

php
//..
public function addColumns(): PowerGridColumns
{

  return PowerGrid::columns()
        ->addColumn('diet', function (Dish $dish) {
            return Diet::from($dish->diet)->labels();
        });
}
//..
public function addColumns(): PowerGridColumns
{

  return PowerGrid::columns()
        ->addColumn('diet', function (Dish $dish) {
            return Diet::from($dish->diet)->labels();
        });
}

Created By Luan Freitas and DanSysAnalyst