Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Eloquent DateTime Formatted Trait (Example for Germany)
<?php
namespace App\Traits;
trait FormattedDate
{
public function initializeFormattedDate()
{
$this->append('formatted_created_at');
$this->append('formatted_created_at_date');
$this->append('formatted_created_at_time');
$this->append('formatted_updated_at');
$this->append('formatted_updated_at_date');
$this->append('formatted_updated_at_time');
}
// created_at
public function getFormattedCreatedAtAttribute()
{
return $this->created_at->format('d.m.Y H:i'); // e.g. 13.04.2020 19:33
}
public function getFormattedCreatedAtDateAttribute()
{
return $this->created_at->format('d.m.Y'); // e.g. 13.04.2020
}
public function getFormattedCreatedAtTimeAttribute()
{
return $this->created_at->format('H:i'); // e.g. 19:33
}
// updated_at
public function getFormattedUpdatedAtAttribute()
{
return $this->updated_at->format('d.m.Y H:i'); // e.g. 13.04.2020 19:33
}
public function getFormattedUpdatedAtDateAttribute()
{
return $this->updated_at->format('d.m.Y'); // e.g. 13.04.2020
}
public function getFormattedUpdatedAtTimeAttribute()
{
return $this->updated_at->format('H:i'); // e.g. 19:33
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment