Create record with custom creation date

Hi there, I want to set a custom creation timestamp for the resource the moment an user opens the create view, and save it with the record without showing it in the form. I tried with different hooks but could not get it working. Any ideas how I can implement this logic without disabling the timestamp in the model? Thanks
7 Replies
Matthew
Matthew6d ago
Do you need the create time stamp to know when the user presses the create button, as opposed to when the record is actually written to row?
Patrick
PatrickOP5d ago
Yes I would like to "abuse" the create timestamp to keep track of the button click instead of when the record is written to the db
Matthew
Matthew5d ago
You could just have a hidden field that will timestamp the form creation time:
DateTimePicker::make('customCreatedAt')
->hidden()
->default(now()),
DateTimePicker::make('customCreatedAt')
->hidden()
->default(now()),
Then use that field $data to inform the database. I'd be cautious of interfering with created_at, I'd have an alternative field.
Patrick
PatrickOP5d ago
Thank @Matthew ! Any specific reasons for your concerns about using the default field?
Matthew
Matthew5d ago
Laravel automates a lot of timestamp stuff for you. I can't think of anything off the top of my head...but maybe someone doing something somewhere that relies on an incremental ID field and created_at to match... I would have to have a very good reason, and no real alternative to manually set a field which 99% of the time, we never touch.
Patrick
PatrickOP5d ago
Thank you for sharing, then I will add a custom field to track the process start, it's just adding more complexity, so I thought it would be more aligned if I use the default timestamp column.
rhysleesdev
rhysleesdev2d ago
Don't use the create page, instead create an action that creates the model. then use the edit form page to allow the user to edit. In ModelResource/Pages/ListModels.php
protected function getHeaderActions(): array
{
return [
Action::make('create')
->label('Create')
->color('primary')
->icon('heroicon-o-plus')
->action('createDraft'),
];
}

public function createDraft(): RedirectResponse | Redirector
{
$model = YourModel::create();

return redirect()->to(ModelResource::getUrl(
name: 'edit',
parameters: ['record' => $model],
isAbsolute: true
));
}
protected function getHeaderActions(): array
{
return [
Action::make('create')
->label('Create')
->color('primary')
->icon('heroicon-o-plus')
->action('createDraft'),
];
}

public function createDraft(): RedirectResponse | Redirector
{
$model = YourModel::create();

return redirect()->to(ModelResource::getUrl(
name: 'edit',
parameters: ['record' => $model],
isAbsolute: true
));
}

Did you find this page helpful?