Add Field default only on Create view for Laravel Nova

Published in Laravel Nova on May 15, 2021

By default, Field::default() will set a default value to a field on Index, Detail, and Create/Attach view. However, you might want to set default only on Create/Attach view, which can be done adding the following to App\Providers\NovaServiceProvider::register():

use Closure;
use Laravel\Nova\Fields\Field;
use Laravel\Nova\Http\Requests\NovaRequest;

Field::macro('defaultOnCreate', function ($callback) {
    return $this->default(function (NovaRequest $request) use ($callback) {
         if ($request->isCreateOrAttachRequest()) {
             return $callback instanceof Closure
                         ? call_user_func($callback, $request)
                         : $callback;
         }
    });
});

To use the macro, you just need to add the following:

use Laravel\Nova\Fields\DateTime;

DateTime::make('Verified At')->defaultOnCreate(now()),