Use a TextInput to input a date in FilamentPHP

Use a TextInput to input a date in FilamentPHP

Using TextInput Instead of DatePicker in FilamentPHP for Custom Date Input, Format, and Validation

  •  First, do not define the $casts property for the date field in your model, for example: 
protected $casts = [
        'date_of_birth' => 'date',
    ];
  •  You should remove this cast when using TextInput for manual date input. 
  • Second, copy the following code block and paste it into your Filament resource.
    Rename the field name (date_of_birth) as needed. 
TextInput::make('date_of_birth')
    ->label('Date of Birth')
    ->placeholder('DD/MM/YYYY')
    ->mask('99/99/9999')
    ->required()
    ->afterStateHydrated(function (TextInput $component, ?string $state): void {
        if ($state) {
            $component->state(
                Carbon::parse($state)->format('d/m/Y')
            );
        }
    })
    ->rules([
        'date_format:d/m/Y',
        'after_or_equal:01/01/1000',
        'before_or_equal:31/12/2999',
    ]);

  • Third, define date mutators in your model to handle the DD/MM/YYYY format.
  • These mutators will automatically convert the input date into the correct database format (Y-m-d).
public function setDateOfBirthAttribute($value)
    {
        $this->attributes['date_of_birth'] = $this->parseDate($value);
    }

    protected function parseDate($value)
    {
        if (!$value) return null;

        try {
            return Carbon::parse(str_replace('/', '-', $value))->format('Y-m-d');
        } catch (\Exception $e) {
            return $value;
        }
    }

Explanation

  • The setDateOfBirthAttribute() method is a mutator that intercepts the date_of_birth value before saving.
  • It uses the helper method parseDate() to:
    • Replace slashes / with dashes - for easier parsing by Carbon.
    • Convert the input date (in DD/MM/YYYY) into a database-compatible format (YYYY-MM-DD).
    • Return null safely if no value is provided or if an error occurs.

Optional Additional Note

This setup replaces the default DatePicker with a TextInput for manual date entry.
 It supports a masked input (DD/MM/YYYY), format validation, and date range rules.
Ros socheath

Ros socheath

Web developer