Skip to content

Data Source Fields โ€‹

This section covers the PowerGrid Data Source fields.

Here you will find:

Introduction โ€‹

Once your Table Data Source method is properly configured, it's time to decide which fields you want to bring as columns to be later displayed on your Table.

Adding Fields โ€‹

To include fields from your data source, call the PowerGrid::fields() inside the fields() method. Then, proceed to chain as many data source fields as you need.

The next example adds the fields id, name, and price, bringing data directly from the database.

php
// app/Livewire/DishTable.php

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

class DishTable extends PowerGridComponent
{
    public function fields(): PowerGridFields
    {
        return PowerGrid::fields()
            ->add('id')
            ->add('name')
            ->add('price');
    }
}

๐ŸŽ‰ Super!

Now, let's check out how to Add Columns.

Custom Fields โ€‹

Sometimes, we need to modify data from the database before showing it on the Table Component.

In addition to a data source field name, PowerGrid::fields()->add() also accepts a closure as a second parameter, allowing you to modify the data coming from the database.

โ— WARNING

Be careful: Data returned in Custom Fields is NOT escaped by default. As a result, your application might be vulnerable to XSS attacks.

It's highly recommended to use Laravel's e() helper to escape data return in Custom Fields.

In the next example, in addition to the database name and price fields, the data source will have two new Custom Fields. These Custom Fields will output the name in UPPER CASE and the price with a 10% discount.

php
// app/Livewire/DishTable.php

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

public function fields(): PowerGridFields
{
    return PowerGrid::fields()
    ->add('id')
    ->add('name')
    ->add('price')
    ->add('name_uppercase', function ($dish) {
        return e(strtoupper($dish->name));
    })
    ->add('price_with_discount', function ($dish) {
        return floatval($dish->price - ($dish->price * 0.1));
    });
}

Formatting Data Examples โ€‹

Sometimes, you need might to display data in a human-friendly way. This is often the case with dates, currencies and boolean values.

Custom Fields provides you a convenient way to prepare and format your data.

Here are examples of some common ways of data formatting.


Date โ€‹

This example adds a new column created_at_formatted to display the formatted created_at datetime column.

php
// app/Livewire/DishTable.php

use PowerComponents\LivewirePowerGrid\Facades\PowerGrid;
use PowerComponents\LivewirePowerGrid\PowerGridFields;
use Illuminate\Support\Carbon;

public function fields(): PowerGridFields
{
    return PowerGrid::fields()
        ->add('created_at') // 2024-01-20 10:05:44
        ->add('created_at_formatted', function ($dish) {
            return Carbon::parse($dish->created_at)->format('d/m/Y H:i'); //20/01/2024 10:05
        });
}

Currency โ€‹

Displaying formatted currency can vastly improve the user experience.

This example adds a new column price_in_eur to display the formatted price.

php
// app/Livewire/DishTable.php

use PowerComponents\LivewirePowerGrid\Facades\PowerGrid;
use PowerComponents\LivewirePowerGrid\PowerGridFields;
use Illuminate\Support\Number;

public function fields(): PowerGridFields
{
  return PowerGrid::fields()
        ->add('price') // 170.90
        ->add('price_in_eur', function ($dish) {
            return Number::currency($dish->price, in: 'EUR', locale: 'pt_PT'); //โ‚ฌ 170,90
        });
}

Boolean โ€‹

Boolean values are not user-friendly.

This example adds a new column in_stock_label to return yes/no instead of true/false in in_stock.

php
// app/Livewire/DishTable.php

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

public function fields(): PowerGridFields
{
  return PowerGrid::fields()
        ->add('in_stock') // 1/0
        ->add('in_stock_label', function ($dish) {
            return $dish->in_stock ? 'Yes' : 'No'; // Yes/No
        });
}

Text summary โ€‹

Large amounts of text can compromise the readability of your Table

This example adds a description_excerpt with only the first 8 words of the description field.

php
// app/Livewire/DishTable.php

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

public function fields(): PowerGridFields
{
    return PowerGrid::fields()
        ->add('description')
        ->add('description_excerpt', function ($dish) {
           return str(e($dish->description))->words(8); //Gets the first 8 words
       });
}

โ— WARNING

Be careful: Data returned in Custom Fields is NOT escaped by default. As a result, your application might be vulnerable to XSS attacks.

It's highly recommended to use Laravel's e() helper to escape data return in Custom Fields.


Sometimes, you may need to render an HTML link inside a Table cell.

This example adds a search_dish_name column with a link to search for a dish name on Google, based on the name field.

php
// app/Livewire/DishTable.php

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

public function fields(): PowerGridFields
{
    return PowerGrid::fields()
        ->add('name')
        ->add('search_dish_name', function ($dish) {
            return sprintf(
                '<a href="https://www.google.com/search?q=%s">Search "%s"</a>',
                urlencode(e($dish->name)),
                e($dish->name)
            );
        });
}

โ— WARNING

Be careful: Data returned in Custom Fields is NOT escaped by default. As a result, your application might be vulnerable to XSS attacks.

It's highly recommended to use Laravel's e() helper to escape data return in Custom Fields.

๐Ÿš€ See it in action

See an interactive example generating an HTML Link.


Dropdown menus allow users to choose an option from a pre-established list. This can be very useful in a grid for manipulating data.

In the example below, we have created a Blade component that receives a list of options and the select category ID of each item. The component is rendered as a Custom Field, and it displays a select input with the category of each dish pre-selected.

php
// app/Livewire/DishTable.php

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

 public function fields(): PowerGridFields
    {
        $options = collect([1 => 'Category A', 2 => 'Category B',  1 => 'Category C' ]);
 
        return PowerGrid::fields()
            ->add('id')
            ->add('name')
            ->add('category_name', function ($dish){
               return Blade::render('<x-select-category type="occurrence" :options=$options  :dishId=$dishId  :selected=$selected/>',
                [
                    'options' => $options, 
                    'dishId' => intval($dish->id), 
                    'selected' => intval($dish->category_id)
                ]);
            });
    }
php
//app/View/Components/SelectCategory.php

namespace App\View\Components;

use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Collection;
use Illuminate\View\Component;

class SelectCategory extends Component
{
    /**
     * Create a new component instance.
     */
    public function __construct(public Collection $options, public int $dishId, public string $selected)
    {
    }

    /**
     * Get the view / contents that represent the component.
     */
    public function render(): View|Closure|string
    {
        return view('components.select-category');
    }
}
php
//resources/views/components/select-category.blade.php

@props(['selected', 'dishId'])
<div>
    <select wire:change="categoryChanged($event.target.value, {{ $dishId }})">
            @foreach ($options as $id => $name)
                <option
                    value="{{ $id }}"
                    @if ($id == $selected)
                        selected="selected"
                    @endif
                >
                    {{ $name }}
                </option>
            @endforeach
    </select>
</div>

๐Ÿš€ See it in action

See an interactive example using Dropdown Menu on a Table.


Image โ€‹

This example demonstrates how to display images within a cell.

php
// app/Livewire/DishTable.php

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

public function fields(): PowerGridFields
{
    return PowerGrid::fields()
        ->add('name')
        ->add('avatar', function ($dish) { 
            return '<img src="' . asset("images/{$dish->id}.jpg") . '">';
        });
}

๐Ÿš€ See it in action

See an interactive example using Images on a Table.


Blade Component โ€‹

Combining Custom Fields with Blade components can be a powerful tool to display customized content inside cells.

You can return a Blade Component as demonstrated below:

php
// app/Livewire/DishTable.php

use PowerComponents\LivewirePowerGrid\Facades\PowerGrid;
use PowerComponents\LivewirePowerGrid\PowerGridFields;
use Illuminate\Support\Facades\Blade; 

public function fields(): PowerGridFields
{
    return PowerGrid::fields()
        ->add('name')
        ->add('rating_stars', fn ($dish) => Blade::render('<x-rate rate="' . $dish->rating . '"/>')); 
}

๐Ÿš€ See it in action

See an interactive example using a Custom Field Blade Component.


Enum โ€‹

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

php
// app/Enums/Diet.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 renders ๐Ÿฝ๏ธ All diets instead of the database value 0.

php
// app/Livewire/DishTable.php

use PowerComponents\LivewirePowerGrid\PowerGridFields;
use App\Enums\Diet;

public function fields(): PowerGridFields
{

  return PowerGrid::fields()
        ->add('name')
        ->add('diet', function ($dish) {
            return Diet::from($dish->diet)->labels();
        });
}

๐Ÿš€ See it in action

See an interactive example using Enums.

Exporting Data โ€‹

Sometimes, it may be necessary to omit certain formatted Columns when exporting data but still show them in the grid. This might be the case with images or HTML links.

To remove these Columns, see Exclude Columns From Exporting.

Created By Luan Freitas and @DanSysAnalyst