> ## Documentation Index
> Fetch the complete documentation index at: https://filamentphp.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Building Tables

export const EditOnGitHub = ({version, path}) => {
  const url = `https://github.com/filamentphp/filament/edit/${version}/${path}`;
  return <div className="not-prose mt-16">
      <a href={url} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-2 text-sm text-gray-500 transition hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor" className="h-4 w-4">
          <path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z" />
        </svg>
        Edit this page on GitHub
      </a>
    </div>;
};

export const Footer = () => {
  const sponsorsByTier = JSON.parse(`{
  "agency_partner": [
    {
      "name": "Kirschbaum",
      "url": "https://kirschbaumdevelopment.com/solutions/filament-development",
      "filename": "kirschbaum.svg"
    }
  ],
  "gold": [
    {
      "name": "Agiledrop",
      "url": "https://www.agiledrop.com/laravel?utm_source=filament",
      "filename": "agiledrop.svg"
    },
    {
      "name": "Baiz.ai",
      "url": "https://baiz.ai",
      "filename": "baiz-ai.svg"
    },
    {
      "name": "CMS Max",
      "url": "https://cmsmax.com?ref=filamentphp.com",
      "filename": "cms-max.svg"
    },
    {
      "name": "Mailtrap",
      "url": "https://mailtrap.io/email-sending?utm_source=community&utm_medium=referral&utm_campaign=filament",
      "filename": "mailtrap.svg"
    },
    {
      "name": "SerpApi",
      "url": "https://serpapi.com/?utm_source=filamentphp",
      "filename": "serpapi.svg"
    }
  ]
}`);
  function shuffleArray(items) {
    const result = [...items];
    for (let index = result.length - 1; index > 0; index--) {
      const randomIndex = Math.floor(Math.random() * (index + 1));
      [result[index], result[randomIndex]] = [result[randomIndex], result[index]];
    }
    return result;
  }
  const sponsors = Object.entries(sponsorsByTier).flatMap(([, sponsors]) => shuffleArray(sponsors));
  return <div className="mt-16 flex flex-col gap-4">
      <h2 className="text-center text-2xl font-medium text-gray-800 dark:text-gray-200">
        Sponsored by
      </h2>

      <div className="not-prose flex flex-wrap items-center justify-center gap-5">
        {sponsors.map(sponsor => <a key={sponsor.name} className="footer-sponsor-card" href={sponsor.url} target="_blank" title={sponsor.name}>
            <img src={`/docs/images/sponsors/footer/${sponsor.filename}`} alt={sponsor.name} noZoom />
            <span className="line-pattern-overlay line-pattern-80" />
          </a>)}

        <a href="https://github.com/sponsors/danharrin" target="_blank" className="footer-sponsor-cta">
          <span className="sponsor-cta-content">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M5 12h14" />
              <path d="M12 5v14" />
            </svg>
            <span>Your logo here</span>
          </span>
          <span className="line-pattern-overlay line-pattern-60" />
        </a>
      </div>
    </div>;
};

<Warning>
  You are currently viewing the documentation for Filament 1.x, which is a previous version of Filament.

  Looking for the current stable version? Visit the [5.x documentation](/docs/5.x/tables).
</Warning>

Filament includes a table builder which can be used to create interactive tables in the admin panel.

Tables have [columns](#columns) and [filters](#filters), which are defined in two methods on the table object.

Here is an example table configuration for a `CustomerResource`:

```php theme={"theme":"gruvbox-dark-hard"}
use Filament\Resources\Tables\Columns;
use Filament\Resources\Tables\Filter;
use Filament\Resources\Tables\Table;

public static function table(Table $table)
{
    return $table
        ->columns([
            Columns\Text::make('name')->primary(),
            Columns\Text::make('email')->url(fn ($customer) => "mailto:{$customer->email}"),
            Columns\Text::make('type')
                ->options([
                    'individual' => 'Individual',
                    'organization' => 'Organization',
                ]),
            Columns\Text::make('birthday')->date(),
            Columns\Boolean::make('is_active')->label('Active?'),
        ])
        ->filters([
            Filter::make('individuals', fn ($query) => $query->where('type', 'individual')),
            Filter::make('organizations', fn ($query) => $query->where('type', 'organization')),
            Filter::make('active', fn ($query) => $query->where('is_active', true)),
        ]);
}
```

## Columns

Resource column classes are located in the `Filament\Resources\Tables\Columns` namespace.

All columns have access to the following customization methods:

```php theme={"theme":"gruvbox-dark-hard"}
Column::make($name)
    ->action($action) // Set Livewire action that should be called when this column is clicked. The current record key will be passed in as a parameter.
    ->getValueUsing($callback = fn ($record) => $record->getAttribute('{column name}')) // Set the callback used to retrieve the value of the column from a given record.
    ->label($label) // Set custom label text for with the column header, which is otherwise automatically generated based on its name. It supports localization strings.
    ->primary() // Sets the column as primary, which emphasises it and links to access a record.
    ->searchable() // Allows the values in this column to be searched.
    ->sortable() // Allows the values in this column to be sorted.
    ->url($url, $shouldOpenInNewTab = false); // Set URL callback that should be used to generate a URL to send the user to when this column is clicked.
```

> Since sorting and searching are done by the database, `sortable()` and `searchable()` will not be fully functional when using a custom `getValueUsing()` callback.

### Displaying Relationship Data

You set up columns that display results from a related model using dot syntax in its name:

```php theme={"theme":"gruvbox-dark-hard"}
Column::make('customer.name');
```

This would check for a `customer` relationship on the parent model and output the related customer's name.

### Calling Actions

You may want something to happen when a cell is clicked. Usually, this is opening a URL, or running a custom Livewire action.

To open a URL when a cell is clicked, a callback is used to generate the destination. For example:

```php theme={"theme":"gruvbox-dark-hard"}
Column::make('website')
    ->url(fn ($record) => $record->website, true);
```

Cells of the above column will display the contents of the record's `website`, and redirect the user to it when they click. The second parameter to `url()`, `true`, means that the website will open in a new tab when clicked.

Alternatively, you may specify a custom Livewire action that should run when the column is clicked. The primary key of the clicked record will be passed as a parameter to the action:

```php theme={"theme":"gruvbox-dark-hard"}
Column::make('username')
    ->action('editUsername');
```

Cells of the above column will call the `editUsername()` Livewire action when clicked.

### Boolean

The `trueIcon()` and `falseIcon()` methods support the name of any Blade icon component, and passes a set of formatting classes to it. By default, the [Blade Heroicons](https://github.com/blade-ui-kit/blade-heroicons) package is installed, so you may use the name of any [Heroicon](https://heroicons.com) out of the box. However, you may create your own custom icon components or install an alternative library if you wish.

```php theme={"theme":"gruvbox-dark-hard"}
Boolean::make($name)
    ->falseIcon($icon = 'heroicon-o-x-circle') // Set the icon that should be displayed when the cell is false.
    ->trueIcon($icon = 'heroicon-s-check-circle'); // Set the icon that should be displayed when the cell is true.
```

### Icon

The `options()` method supports the names of any Blade icon components, and passes a set of formatting classes to them. By default, the [Blade Heroicons](https://github.com/blade-ui-kit/blade-heroicons) package is installed, so you may use the name of any [Heroicon](https://heroicons.com) out of the box. However, you may create your own custom icon components or install an alternative library if you wish.

```php theme={"theme":"gruvbox-dark-hard"}
Icon::make($name)
    ->options($options = []); // Set the icon that should be displayed when the cell is a given value.
```

Here is an example usage of this column:

```php theme={"theme":"gruvbox-dark-hard"}
Icon::make('status')
    ->options([
        'heroicon-s-check-circle' => fn ($status) => $status === 'accepted', // When the `status` is `accepted`, render the `check-circle` Heroicon.
        'heroicon-s-x-circle' => fn ($status) => $status === 'declined', // When the `status` is `declined`, render the `x-circle` Heroicon.
        'heroicon-s-clock' => fn ($status) => $status === 'pending', // When the `status` is `pending`, render the `clock` Heroicon.
    ]);
```

### Image

```php theme={"theme":"gruvbox-dark-hard"}
Image::make($name)
    ->disk($disk) // Set a custom disk that images should be read from.
    ->height($height = 40) // Set the height of the image in pixels.
    ->rounded() // Make the image preview fully rounded.
    ->size($size) // Set the height and width of the image in pixels.
    ->width($width); // Set the width of the image in pixels.
```

### Text

```php theme={"theme":"gruvbox-dark-hard"}
Text::make($name)
    ->currency($symbol = '€', $decimalSeparator = '.', $thousandsSeparator = ',', $decimals = 2) // Format values in this column in a currency format.
    ->date($format = 'F j, Y') // Format values in this column as dates, using PHP date formatting tokens.
    ->dateTime($format = 'F j, Y H:i:s') // Format values in this column as date-times, using PHP date formatting tokens.
    ->default() // Set the default value for when this field does not exist.
    ->formatUsing($callback = fn ($value) => $value) // Set the callback used to format the value of the column.
    ->limit($limit) // Truncate the value of this column to a certain number of characters.
    ->options($options = []); // Set the key-value array of available values that this column could hold.
```

> Other column types are coming soon.

### Developing Custom Column Types

To create a new column type, which may be used in any table, you may generate a class and cell view using:

```bash theme={"theme":"gruvbox-dark-hard"}
php artisan make:filament-column Avatar --resource
```

Alternatively, simple custom columns may be created using a `View` component, and passing the name of a cell `$view` in your app:

```php theme={"theme":"gruvbox-dark-hard"}
Columns\View::make($view)
    ->data($data = []); // Set the key-value array of available data that the view has access to.
```

## Filters

Filters are used to scope results in the table. Here is an example of a filter at allows only customers with a `type` of `individual` to be shown in the table:

```php theme={"theme":"gruvbox-dark-hard"}
Filter::make('individuals', fn ($query) => $query->where('type', 'individual'));
```

They have access to the following customization options:

```php theme={"theme":"gruvbox-dark-hard"}
Filter::make($name, $callback = fn ($query) => $query)
    ->label($label); // Set custom label text for with the filter, which is otherwise automatically generated based on its name. It supports localization strings.
```

You can define a default filter to be applied when no other filter is selected by the user by calling `defaultFilter()` on the `Table` object:

```php theme={"theme":"gruvbox-dark-hard"}
public static function table(Table $table)
{
    return $table
        ->columns([
            // ...
        ])
        ->filters([
            Filter::make('individuals', fn ($query) => $query->where('type', 'individual')),
            Filter::make('organizations', fn ($query) => $query->where('type', 'organization')),
            Filter::make('active', fn ($query) => $query->where('is_active', true)),
        ])
        ->defaultFilter('individuals');
}
```

### Reusable Filters

You may wish to create a filter that you may reuse across multiple tables.

To create a reusable filter, you may use the following command:

```bash theme={"theme":"gruvbox-dark-hard"}
php artisan make:filament-filter ActiveFilter --resource
```

This will create a new filter in the `app/Filament/Resources/Tables/Filters` directory:

```php theme={"theme":"gruvbox-dark-hard"}
<?php

namespace App\Filament\Resources\Tables\Filters;

use Filament\Tables\Filter;

class ActiveFilter extends Filter
{
    protected function setUp()
    {
        $this->name('active');
    }

    public function apply($query)
    {
        return $query;
    }
}
```

You may modify the filter's query in the `apply()` method of that class:

```php theme={"theme":"gruvbox-dark-hard"}
public function apply($query)
{
    return $query->where('is_active', true);
}
```

> Currently, filters are static and only one may be applied at a time. Parameter-based filters and support for applying multiple filters at once is coming soon.

## Context Customization

You may customize tables based on the page they are used. To do this, you can chain the `only()` or `except()` methods onto any column or filter.

```php theme={"theme":"gruvbox-dark-hard"}
use App\Filament\Resources\CustomerResource\Pages;
use Filament\Resources\Tables\Filter;
use Filament\Resources\Tables\Table;

public static function table(Table $table)
{
    return $table
        ->filters([
            Filter::make('individuals', fn ($customer) => $customer->type === 'individual')
                ->only(Pages\ListCustomers::class),
        ]);
}
```

In this example, the `individuals` filter will `only()` be available on the `ListCustomers` page.

```php theme={"theme":"gruvbox-dark-hard"}
use App\Filament\Resources\CustomerResource\Pages;
use Filament\Resources\Tables\Columns;
use Filament\Resources\Tables\Table;

public static function table(Table $table)
{
    return $table
        ->columns([
            Columns\Text::make('name')
                ->except(Pages\ListCustomers::class, fn ($column) => $column->primary()),
        ]);
}
```

In this example, the `name` column will be primary, `except()` on the `ListCustomers` page.

This is an incredibly powerful pattern, and allows you to completely customize a table contextually by chaining as many methods as you wish to the callback.

<EditOnGitHub version="1.x" path="docs/04-tables.md" />

<Footer />
