you'll have to check some formats yourself i'm afraid.
but it's actually for the best: as US formats differ from others you can sometimes get Y-m-d or d-m-Y or m-d-Y
Having a date like 08-07-18 could be Aug 7, or Jul 8
I usually do something like:
public function setDateAttribute($date)
{
$approvedFormats = [ 'Y-m-d', 'd-m-Y', 'y-m-d', 'd-m-y', 'd M Y'];
foreach($approvedFormats as $format) {
if($carbon = Carbon::createFromFormat($format, $date)) {
$this->attributes['date'] = $carbon->format('Y-m-d');
}
}
}
Checking a few formats to see what the client inputted this time, and reformatting it to Y-m-d before saving to the model.
/**
* Use the Laravel validation to validate a value.
*
* @param $value the value to test
* @param $rules Laravel standard rules: 'required|numeric'
* @return bool
*/
function validateValue($value,$rules)
{
//needs to be an assoc
$assoc = ['value'=>$value];
$validator = Validator::make($assoc, [
'value' => $rules,
]);
return !$validator->fails();
}
Figured I should just use the Laravel code. Genius or lunacy?
strtotime will return a number below zero when the date is invalid such as common in MySQL 0000-00-00 00:00:00. Make sure you pass an object type date or carbon:
return strtotime(date or carbon object) < 0 ? null : date