@Alk90
php, mysql, jquery, css, html, api

Как правильно в Laravel объединить дату и время если они находятся в разных полях?

Всем привет. У меня в таблице есть два поля, date и time (время может быть NULL).
Как в Laravel создать модель так, чтобы дата и время объединились в Datetime?

У меня вот такой вариаант, но кажется он плохой.

class Order extends Model{

    public function getDateTime(){
        $unixtime = strtotime($this->date . (!is_null($this->time) ? ' '. $this->time : ''));
        return new DateTime($unixtime);
    }

    protected $casts = [];

}
  • Вопрос задан
  • 147 просмотров
Пригласить эксперта
Ответы на вопрос 1
@iljaGolubev
use Illuminate\Database\Eloquent\Casts\Attribute;

class Order extends Model{

    protected $casts = ['date_time' => 'datetime:Y-m-d H:00'];

    function dateTime(): Attribute
    {
         return Attribute::make(
            get: fn () => $this->castAttribute(
                  'date_time',
                  ($this->date ?: '1970-01-01') . ' ' . ($this->time ?: '10:00:01')
               )
            )
        );
    }

}

# php artisan tinker
App\Models\Order::first()->date_time;
# = Illuminate\Support\Carbon @0 {#7053
#   date: 1970-01-01 00:00:00.0 UTC (+00:00),
#  }


https://laravel.com/docs/10.x/eloquent-mutators#de...
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы