Laravel: cast para fechas

Creamos app/Casts/DateFormat.php con lo siguiente:

<?php

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Carbon\Carbon;

class DateFormat implements CastsAttributes
{
/**
* private @var format
*/
private string $getFormat = 'd/m/Y H:i';
private string $setFormat = 'Y-m-d H:i';

/**
 * Cast the given value.
 *
 * @param  \Illuminate\Database\Eloquent\Model  $model
 * @param  string  $key
 * @param  mixed  $value
 * @param  array  $attributes
 * @return array
 */
public function get($model, $key, $value, $attributes)
{
    return strlen($value)
        ? Carbon::parse($value)->format($this->getFormat)
        : null;
}

/**
 * Prepare the given value for storage.
 *
 * @param  \Illuminate\Database\Eloquent\Model  $model
 * @param  string  $key
 * @param  array  $value
 * @param  array  $attributes
 * @return string
 */
public function set($model, $key, $value, $attributes)
{
    return strlen($value)
        ? Carbon::parse($value)->format($this->setFormat)
        : null;
}
}

Y en el modelo lo usamos así:

protected $casts = [
'created_at' => \App\Casts\DateFormat::class,
];

Deja un comentario