Skip to content

Instantly share code, notes, and snippets.

@rslhdyt
Last active September 12, 2019 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rslhdyt/ea9d3f764abc72a6242ffe1c159c052e to your computer and use it in GitHub Desktop.
Save rslhdyt/ea9d3f764abc72a6242ffe1c159c052e to your computer and use it in GitHub Desktop.
[Date Mutator] Traits helper to format date object #laravel #php #traits
<?php
namespace App\Models\Traits;
use Carbon\Carbon;
trait DateFormater
{
public function appDate($attribute, $format = null)
{
if ($this->$attribute == null) {
return null;
}
$format = $this->getAppDateFormat($format);
$datetime = $this->checkAndConvertCarbon($attribute);
return $datetime->format($format);
}
public function appDateTime($attribute, $format = null)
{
if ($this->$attribute == null) {
return null;
}
$format = $this->getAppDateTimeFormat($format);
$datetime = $this->checkAndConvertCarbon($attribute);
return $datetime->format($format);
}
private function getAppDateFormat($format = null)
{
return $format ?? config('koperasi-io.date_format.php');
}
private function getAppDateTimeFormat($format = null)
{
return $format ?? config('koperasi-io.datetime_format.php');
}
private function checkAndConvertCarbon($attribute)
{
$datetime = is_string($attribute) ? $this->$attribute : $attribute;
if (!$datetime instanceof Carbon) {
// throw new \Exception('The datetime should instance of carbon class');
$datetime = Carbon::parse($datetime);
}
return $datetime;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment