Last active
August 28, 2019 13:43
-
-
Save epalmans/261bcc933f094234a19f4bb24bbec501 to your computer and use it in GitHub Desktop.
Trait to map validated dates from Laravel FormRequest to Carbon instances
This file contains 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\Traits; | |
use Illuminate\Support\Arr; | |
use Illuminate\Support\Str; | |
use Illuminate\Support\Carbon; | |
trait TransformValidatedDates | |
{ | |
public function validated() | |
{ | |
$dateFormatMap = $this->fieldsToMapWithDateFormat(); | |
return collect(parent::validated())->map(function ($value, $field) use ($dateFormatMap) { | |
$fieldWithDateFormat = $dateFormatMap->get($field); | |
if (is_null($fieldWithDateFormat)) { | |
return $value; | |
} | |
return $fieldWithDateFormat | |
? Carbon::createFromFormat($fieldWithDateFormat, $value)->startOfDay() | |
: Carbon::parse($value); | |
})->all(); | |
} | |
private function fieldsToMapWithDateFormat() | |
{ | |
return collect($this->validator->getRules())->map(function ($rules) { | |
$daterule = Arr::first($rules, function($rule) { | |
return is_string($rule) && | |
$rule == 'date' || Str::startsWith($rule, 'date_format:'); | |
}); | |
return $daterule | |
? explode(':', $daterule)[1] ?? '' | |
: null; | |
})->reject(function ($dateformat) { | |
return is_null($dateformat); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment