Skip to main content
Tutorial Free

Filament: Calculate/Show Age Based on Birth Date Field

March 28, 2023
4 min read

Tutorial last revisioned on October 27, 2024 with Livewire 3 and Filament 3

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;
use Filament\Forms\Set;
 
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()
->live()
->afterStateUpdated(function (Set $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 adding live(). By default, Filament does not add .live to every field, but we need this field's value to be set in the component immediately, so we add 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.

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

IJ
Iam Joker ✓ Link copied!

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?

PK
Povilas Korop ✓ Link copied!

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.

DG
DIOMEDES GARRUCHO ✓ Link copied!

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.

N
Nerijus ✓ Link copied!

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']),
VS
Vasily Sergeev ✓ Link copied!

Hi in filament 3 not work to me...

App\Filament\Resources\StudentResource::App\Filament\Resources{closure}(): Argument #1 ($set) must be of type Closure, Filament\Forms\Set given, called in /Users/sergeev/Php/GitVerse/talent/vendor/filament/support/src/Concerns/EvaluatesClosures.php on line 35

N
Nerijus ✓ Link copied!

in v3 set isn't closure, check the

VS
Vasily Sergeev ✓ Link copied!

Big thx u bro! I broke my whole brain, but I couldn't figure out why it wasn't working! You need to update the documentation of this article with a note for v3 without this. Work for me.

SF
Steve Fontaine ✓ Link copied!

Hello, when dealing with date of birth I run in the issue of timezone changing the date entered by the user as I am using the macro '''DateTimePicker::configureUsing(fn (DateTimePicker $component) => $component->timezone(auth()->user()?->timezone ?? config('app.timezone_display')));'''

Any idea on how to deal with this for non timezoned date input ?

SF
Steve Fontaine ✓ Link copied!

I actually found the solution: on the form field just force the timezone to UTC:

DatePicker::make("date_of_birth") ->timezone('UTC')

Easy !

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.