DEV Community

Mior Muhammad Zaki
Mior Muhammad Zaki

Posted on • Originally published at crynobone.com

Extending default Fields on Laravel Nova

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'),
Enter fullscreen mode Exit fullscreen mode

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');
    }
}
Enter fullscreen mode Exit fullscreen mode

And your fields can be simplify to:

use App\Nova\Fields\DateTime;

DateTime::make('Created At'),
DateTime::make('Updated At'),
Enter fullscreen mode Exit fullscreen mode

Top comments (0)