Skip to content

Comments

[12.x] Add callback to customize fresh timestamp creation for all models#58620

Closed
AndrewMast wants to merge 1 commit intolaravel:12.xfrom
AndrewMast:fresh-timestamps-using
Closed

[12.x] Add callback to customize fresh timestamp creation for all models#58620
AndrewMast wants to merge 1 commit intolaravel:12.xfrom
AndrewMast:fresh-timestamps-using

Conversation

@AndrewMast
Copy link
Contributor

This is an alternative to PR #58614.

Why

Like @aimeos pointed out in the PR, sometimes the implementation for creating fresh timestamps needs to be changed. While this can be accomplished by overriding the freshTimestamp method for a specific model, you might need to change the behavior for all models, in the case with storing timestamp values into a SQL Server database.

This PR adds a Model::freshTimestampsUsing($callback); method to accomplish this. It also adds a Model::freshTimestampsWithoutMicroseconds(); method to simply change the fresh timestamp logic to Date::now()->startOfSecond(), like @aimeos originally had in their PR.

What

Added the following to HasTimestamps trait to allow for a custom fresh timestamps callback:

/**
 * The callback that should be used to create fresh timestamps.
 *
 * @var (\Closure(): \Illuminate\Support\Carbon)|null
 */
public static $freshTimestampsCallback;


/**
 * Set a callback that should be used to create fresh timestamps.
 *
 * @param  \Closure(): \Illuminate\Support\Carbon  $callback
 * @return void
 */
public static function freshTimestampsUsing($callback)
{
    static::$freshTimestampsCallback = $callback;
}

/**
 * Create fresh timestamps without microseconds.
 *
 * @return void
 */
public static function freshTimestampsWithoutMicroseconds()
{
    static::$freshTimestampsCallback = fn () => Date::now()->startOfSecond();
}

And updated freshTimestamp to use the callback:

/**
 * Get a fresh timestamp for the model.
 *
 * @return \Illuminate\Support\Carbon
 */
public function freshTimestamp()
{
    if (static::$freshTimestampsCallback) {
        return call_user_func(static::$freshTimestampsCallback);
    }

    return Date::now();
}

Tests

Still working on tests, would appreciate tips as I don't write tests often.

@taylorotwell
Copy link
Member

Merged other PR.

@aimeos
Copy link
Contributor

aimeos commented Feb 5, 2026

@AndrewMast Thanks but I only wanted to get a consistent default behavior across all supported databases. Nevertheless, the changing the timestamp format across all models can be useful if someone needs high resolution timestamps with microseconds. Only the freshTimestampsWithoutMicroseconds() method isn't necessary.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants