laravel-best-practices icon indicating copy to clipboard operation
laravel-best-practices copied to clipboard

Date formatting

Open clemblanco opened this issue 6 years ago • 2 comments

Is this really working?

// Model
protected $dates = ['ordered_at', 'created_at', 'updated_at']
public function getSomeDateAttribute($date)
{
    return $date->format('m-d');
}

// View
{{ $object->ordered_at->toDateString() }}
{{ $object->ordered_at->some_date }}

Is it really adding a property on the fly to the Carbon object?

$object->ordered_at->some_date doesn't really read fluent...

clemblanco avatar Dec 21 '18 11:12 clemblanco

I believe it'd read $object->some_date instead of being appended to $object->order_at, but I could be wrong..

// Model
protected $dates = ['ordered_at', 'created_at', 'updated_at']
public function getSomeDateAttribute()
{
    return $this->ordered_at->format('m-d');
}

// View
{{ $object->ordered_at->toDateString() }}
{{ $object->some_date }}

Here's what I'd expect https://laravel.com/docs/5.8/eloquent-mutators#defining-an-accessor

CarterBland avatar Apr 29 '19 16:04 CarterBland

@CarterBland @clemblanco True, it should be $object->some_date to actually access the accessor. $object->ordered_at will simply return a Carbon instance.

This example also lacks understanding from many perspectives.

  • It makes no sense to call $object->ordered_at->toDateString() if there was no format applied.
  • It would make no sense to override the attribute ordered_at with getOrderedAtAttribute where the original value of ordered_at becomes inaccessible on first sight. This could be solved by using $object->attributes['ordered_at'], but that is the raw state of the attribute which only makes sense if it is intentional.

If 3 dates are available, and to format one date, it should be named similar to the original attribute, e.g.

protected $dates = ['ordered_at', 'created_at', 'updated_at']
public function getOrderedAtFormatAttribute()
{
    return $this->ordered_at->format('m-d');
}

// View
{{ $object->ordered_at_format }}
{{ $object->ordered_at_format->toDateString() }}

wize-wiz avatar Aug 20 '20 18:08 wize-wiz