Filament: Calculate/Show Age Based on Birth Date Field

In this quick tutorial for Filament I will show you how to show calculate the "age" value from the "birth_date" field, show the age in the table, and customize its color.

It is the answer to the question I received in a comment on my YouTube channel:

youtube comment

This is the result we will be working towards:

birthday today

First, we have one additional field to the User table date_of_birth and will be using UserResource for Filament resources.


Auto-Set Age Field in the Form

In our UserResource, we have simple three fields:

  • name
  • date of birth
  • age

app/Filament/Resources/UserResource.php:

use Closure;
use Carbon\Carbon;
 
class UserResource extends Resource
{
protected static ?string $model = User::class;
 
protected static ?string $navigationIcon = 'heroicon-o-collection';
 
public static function form(Form $form): Form
{
return $form
->schema([
Forms\Components\TextInput::make('name')
->required(),
Forms\Components\DatePicker::make('date_of_birth')
->required()
->reactive()
->afterStateUpdated(function (Closure $set, $state) {
$set('age', Carbon::parse($state)->age);
}),
Forms\Components\TextInput::make('age')
->disabled()
->dehydrated(false),
]);
}
// ...
}

So what do we do here? Visually the age input exists but we just disable it, because it will be set automatically when the date_of_birth is set. Also it is set to dehydrated(false) so it wouldn't be inserted into DB.

Now for the main birth_date field:

  • First, it is set to be a DatePicker
  • Then obviously it's a required field
  • Next, we set this field to be reactive. By default, Filament adds .defer to every field, but we need this field's value to be set in the component immediately, so we remove it.
  • And lastly: after the value is changed, we use Livewire magic action $set to set the age field with age value.

This is how the form looks like:

create form


Showing Age in the Table

Show the user's age on the list page is very easy. We just need to define an accessor that will calculate age from the date_of_birth field in the DB using Carbon.

app/Models/User.php:

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Casts\Attribute;
 
class User extends Authenticatable
{
// ...
public function age(): Attribute
{
return Attribute::make(
get: fn() => Carbon::parse($this->date_of_birth)->age,
);
}
}

Now we can show age in the table as we would with every other field.

app/Filmanet/Resources/UserResource.php:

class UserResource extends Resource
{
// ...
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('name'),
Tables\Columns\TextColumn::make('age'),
])
->filters([
//
])
->actions([
Tables\Actions\EditAction::make(),
])
->bulkActions([
Tables\Actions\DeleteBulkAction::make(),
]);
}
// ...
}

age field in the table


Colored Column if Birthday

One extra thing: let's add a background color to the age cell if the user's birthday is today. First, we need to cast date_of_birth to date so that we could use all Carbon features.

app/Models/User.php:

class User extends Authenticatable
{
// ...
protected $casts = [
'email_verified_at' => 'datetime',
'date_of_birth' => 'date',
];
 
public function age(): Attribute
{
return Attribute::make(
get: fn() => Carbon::parse($this->date_of_birth)->age,
);
}
}

This way we can use the isBirthday() Carbon method to check if the user's birthday is today and use the extraAttributes() method on the field set the background.

app/Filament/Resources/UserResource.php:

class UserResource extends Resource
{
// ...
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('name'),
Tables\Columns\TextColumn::make('age')
->extraAttributes(function (User $record) {
if ($record->date_of_birth->isBirthday()) {
return ['class' => 'bg-success-500'];
}
return [];
}),
])
->filters([
//
])
->actions([
Tables\Actions\EditAction::make(),
])
->bulkActions([
Tables\Actions\DeleteBulkAction::make(),
]);
}
// ...
}

Now, for every user who has a birthday today, the background color will be green.

birthday today background


If you want more Filament examples, you can find more real-life projects on our FilamentExamples.com.

avatar

how to make it appear on another page, I have a case after that age it appears the user wants to edit, but on like page/ViewUser.php That age cannot appear. can you help me fix my problem?

avatar

It's hard to answer in a comment, without seeing the full code example. But pretty sure that on the ViewUser page you can customize the data shown, just read the Filament docs for all the possibilities. Or, put your code snippets in the official Filament discord and people will help you there.

avatar

Hi Povilas! Thanks for this article. What would be the best way to sort by age in Filament? Right now i get an error saying that the age field does not exist.

avatar

Filament only allows database-powered sorting and searching. In this case for the age column we can pass the date_of_birth to a sortable method.

Tables\Columns\TextColumn::make('age')
    ->sortable(['date_of_birth']),

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 59 courses (1056 lessons, total 42 h 44 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials