Extending default Fields on Laravel Nova

Published in Laravel Nova on Dec 21, 2020

Each project doesn't always expect the same set of default and you might have a requirement to customise Laravel Nova default behavior. For example setting default datetime format for DateTime field.

Imagine you have the following scenario:

use Laravel\Nova\Fields\DateTime;

DateTime::make('Created At')->sortable()->format('D-M-yyyy H:m'),
DateTime::make('Updated At')->sortable()->format('D-M-yyyy H:m'),

Instead of writing ->sortable()->format('D-M-yyyy H:m') for each field you can override the field by adding App\Nova\Fields\DateTime and add the following code:

<?php

namespace App\Nova\Fields;

class DateTime extends \Laravel\Nova\Fields\DateTime 
{
    /**
     * Create a new field.
     *
     * @param  string  $name
     * @param  string|null  $attribute
     * @param  mixed|null  $resolveCallback
     * @return void
     */
    public function __construct($name, $attribute = null, $resolveCallback = null)
    {
        parent::__construct($name, $attribute, $resolveCallback);
      
        $this->sortable()->format('D-M-yyyy H:m');
    }
}

And your fields can be simplify to:

use App\Nova\Fields\DateTime;

DateTime::make('Created At'),
DateTime::make('Updated At'),