Dear @pimski perhaps you could make use of Laravel getAttribute as well ?
Something like this:
public function getDateAttribute($date)
{
return Carbon::parse($date)->format('d-m-Y');
}
And in your views if you call $entity->date you will get the desired result ?
Alternatively if you would like more control and flexibility on how you retrieve the date, perhaps you could try this:
- Create a dedicated DateFormatter like this:
<?php
namespace App\Formatters;
use Carbon\Carbon;
class DateFormatter
{
/**
* Carbon $date
*/
private $date;
/**
* Inject Date from Entity
*/
public function __construct($date)
{
$this->date = Carbon::parse($date);
}
/**
* Format Date for Form Use
*/
public function forForm()
{
return $this->date->format('d-m-Y');
}
/**
* Format date for Profile
*/
public function forHumans()
{
return $this->date->diffForHumans();
}
}
And then on your Entity you could change the getDateAttribute method to something like this:
public function getDateAttribute($date)
{
return new DateFormatter($date);
}
This will allow you to format the dates in many different ways the view could require by simply calling:
{{ $entity->date->forForm() }}
Here is a video here on Laracasts that explains this method in more detail: https://laracasts.com/series/whip-monstrous-code-into-shape/episodes/6
Kindly note the above stated code was not tested, and it's only to serve as an idea :)