Last active
September 12, 2019 16:29
-
-
Save rslhdyt/ea9d3f764abc72a6242ffe1c159c052e to your computer and use it in GitHub Desktop.
[Date Mutator] Traits helper to format date object #laravel #php #traits
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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