Calculate the difference between 2 dates
I have 2 columns start_date and end_date. I want to calculate the time difference between them and write them to the database
My code :
TextInput::make('total_of_days')
->disabled()
->formatStateUsing(fn(\Closure $get) => Carbon::parse($get('start_date'))->diffInDays(Carbon::parse($get('end_date'))))
->dehydrated(true)
->required(),
But not working.
12 Replies
Can u confirm ur model has 'total_of_days' in $fillable?
yeah
data is added. but its value is written as 0
Try this,
It will be 0 because you haven't made the original fields reactive.
You need to provide the whole code when asking for help
This code working. Tkanks again))
->dehydrateUsing(fn(\Closure $get) => Carbon::parse($get('start_date'))->diffInDays(Carbon::parse($get('end_date')))) i forget add this line
Could someone help me with a similar problem? on filament v3
->schema([
Forms\Components\Select::make('customer_id')
->relationship('customer', 'full_name')
->required(),
Forms\Components\DatePicker::make('rental_date')->label(__('Rental start date'))
->live()
->required(),
Forms\Components\DatePicker::make('return_date')->label(__('Rental end date'))
->live()
->required(),
Forms\Components\TextInput::make('total_of_days')
->disabled()
//->formatStateUsing(fn(\Closure $get) => Carbon::parse($get('rental_date'))->diffInDays(Carbon::parse($get('return_date'))))
//->dehydrateUsing(fn(\Closure $get) => Carbon::parse($get('rental_date'))->diffInDays(Carbon::parse($get('return_date'))))
->dehydrated(true)
->required(),
Please open a new discussion
I would calculate this also in an observer or something, why would you do this in a form for a user? Maybe just show a value with a placeholder or sth, but calculate the def value somewhere in the backend.
Maybe it will be useful to someone.
return $form
->schema([
Forms\Components\Select::make('customer_id')
->relationship('customer', 'full_name')
->required(),
Forms\Components\DatePicker::make('rental_date')->label(__('Rental start date'))
//->default(now())
->required()
->live(true)
->afterStateUpdated(function (Get $get, Set $set) {
self::updateTotalsDays($get, $set);
}),
Forms\Components\DatePicker::make('return_date')->label(__('Rental end date'))
->default(fn (Get $get) => $set('rental_date'))
->required()
->live(true)
->afterStateUpdated(function (Get $get, Set $set) {
self::updateTotalsDays($get, $set);
}),
Forms\Components\TextInput::make('total_of_days')
->numeric()
->readOnly()
]);
}
public static function updateTotalsDays(Get $get, Set $set): void
{
$days = Carbon::parse($get('rental_date'))->diffInDays(Carbon::parse($get('return_date')));
$set('total_of_days', $days);
}