Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

richardh's avatar

Set a date in model

I was wondering how would I set the date in the model when there was a certain input present.

For example i am updating a model and wanted to set the date to now()

0 likes
3 replies
tykus's avatar

You could use the model's events to intercept the updating event and set a value on the instance before it is persisted. There are a small number of different approaches from a boot() method and Closure, to a $dispatchesEvents and Event Handler class; the suitability of a particular approach would depend on the complexity of the check you are performing.

EDIT example of a Closure approach

protected static function boot()
{
        static::updating(function ($model) {
            if ($model->someCondition) {
                $model->update(['date' => now()]);
            }
        });
}
richardh's avatar

I have gone for this approach do you think it will be ok?

 if($request->has('ofs')){
            $data['ofs_updated'] = \Carbon\Carbon::now();
        }
tykus's avatar
tykus
Best Answer
Level 104

Oh, I missed the certain input part!

Yes, when it is dependent on the request, then your way is more appropriate. (Don't forget to save()

FWIW, there is a now() helper method which returns the same Carbon instance as \Carbon\Carbon::now(); - looks neater in my opinion.

1 like

Please or to participate in this conversation.