Skip to content

Instantly share code, notes, and snippets.

@epalmans
Last active August 28, 2019 13:43
Show Gist options
  • Save epalmans/261bcc933f094234a19f4bb24bbec501 to your computer and use it in GitHub Desktop.
Save epalmans/261bcc933f094234a19f4bb24bbec501 to your computer and use it in GitHub Desktop.
Trait to map validated dates from Laravel FormRequest to Carbon instances
<?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