How to display the next working day with Laravel Nova

Background

When using Laravel Nova, you might want to populate a date field with a date in the future, for example, if you have tasks, you might want to explore having a due date which is two working days from now. Another nice to have is to display dates in human friendly format.

In this example, we show you how to achieve just that. It’s quite a lot of code but will lead to a beautiful user interface.

Snippet

DateTime::make('Due At')
    ->withMeta(['value' => $this->due_at ?? nextWorkingDay(Carbon::now(), settings('task_default_due_at'))
            ->toDateString()])
    ->hideFromIndex()
    ->hideWhenUpdating()
    ->hideFromDetail(),

Text::make('Due At', function () {
    if ($this->due_at) return $this->due_at->diffForHumans();
})->hideWhenCreating()->hideWhenUpdating()->hideFromIndex(),

DateTime::make('Due At')->hideFromIndex()->hideWhenCreating()->hideFromDetail(),
function nextWorkingDay(Carbon $date, $days): Carbon
{
    $date->addWeekdays($days);

    while (in_array($date->toDateString(), holidays())) {
        $date->addWeekday();
    }
    return $date;
}
function holidays()
{
    $holidays = Event::where('type', 'holiday')->pluck('start')->map(function ($holiday) {
        return $holiday->toDateString();
    });
    return $holidays->toArray();
}

Explanation

  • Three fields are required!
    1. A field to automatically calculate the future date
    2. Another to display the date in human friendly format
    3. A third to allow updating
  • Carbon’ `addWeekdays` method is used
  • A function maps over a database table populated with current holidays, if a holiday is found, another weekday is added

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top