ToggleColumn: Only One Active Record (Set Others to False)

2024-05-06

If you have a ToggleColumn in the table and want to ensure there's only ONE row in the database with true value, you can auto-set others to false.

All you need to do is use the function beforeStateUpdated() on the ToggleColumn and run one update Eloquent query inside.

For example, if you have a DB column users.active as boolean, here's the code:

app/Filament/Resources/UserResource.php:

public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('name'),
Tables\Columns\ToggleColumn::make('active')
->beforeStateUpdated(function (User $record) {
User::where('id', '!=', $record->id)->update(['active' => false]);
}),
])

The table will refresh automatically.

A few of our Premium Examples: