pilat
750
6
Laravel

Is there a nice way to handle empty dates in templates?

Posted 1 year ago by pilat

Hi,

Let say, I have a nullable Date or DateTime field in my DB. Eloquent exports it to templates as Carbon object, so, I can freely setup formatting:

<td>{{ $record->some_date_field->format('d.m.Y') }}</td>

This is very convenient, and I'd prefer to have this option available.

The problem is when 'm trying to display dates from those records, that have it empty (or null; or zero, if I store timestamps). Here's a piece of real code:

    public function getCompleteTillCarbonAttribute()
    {
        return \Carbon\Carbon::createFromTimestamp($this->complete_till);
    }
<td>{{ $task->complete_till_carbon->format('Y-m-d') }}</td>

When original complete_till is 0, I'll have 1970-01-01 date on the output. To avoid this, I should do one of the following:

  1. Use conditions in blade:
<td>{{ 0 === $task->complete_till ? 'n/a' : $task->complete_till_carbon->format('Y-m-d') }}</td>
  1. Make a function that returns date as string:
    public function getCompleteTillStringAttribute()
    {
    return 0 === $this->complete_till
        ? 'n/a'
        : date('d.m.Y', $this->complete_till); // don't see any use for Carbon in this case
    }

Neither way is very elegant, I wold say. I'd prefer the template to be in charge for appearance, but not to have that ugly ternary condition operator…

Something like this: {{ $record->a_date->format('d.m.Y')->ifEmpty('n/a') }}, or this: {{ $record->a_date->format('d.m.Y', 'n/a') }};

Do anyone have good solution to the issue?

Please sign in or create an account to participate in this conversation.