laravel-best-practices
laravel-best-practices copied to clipboard
Date formatting
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...
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 @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_atwithgetOrderedAtAttributewhere the original value ofordered_atbecomes 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() }}