Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Swaz's avatar
Level 20

Set date attribute from a date and time input

I have a separate date and time input on my form. And I'd like to save them both to a single DATETIME column in the database. In this example, the 'date' attribute is the DATETIME column.

For some reason, $this->date and $this->time return null, but I can access other attributes on the model in that way, for example $this->title works as expected.

Is there any way I can set the date field to include the date and time? I also tried to set the date with a model 'saving' event, but I couldn't get that to work either.

<input type="date" name="date">
<input type="time" name="time">
//model
protected $fillable = ['title', 'date'];

protected $dates = ['date'];

public function setDateAttribute($value)
{
    $this->attributes['date'] = $this->date.' '.$this->time;

    // dd($value) = 2016-05-19
    // dd($this->date) = null
    // dd($this->time) = null
    // dd($this->title) = 'My Title'
}
0 likes
1 reply
awarren's avatar

Here's one simple example. It uses a public method on the model to set a timestamp based on text values.

The model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Mydate extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'dates';
    
    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['created_at', 'updated_at', 'test'];
    
    public function setDate($date, $time)
    {
        $this->test = strtotime("$date $time");
    }
}

A simple use case:

>>> $date = date('Y-m-d')
=> "2016-05-19"
>>> $time = date('H:i')
=> "20:35"
>>>
>>> $mydate = new App\Mydate
=> App\Mydate {#682}
>>>
>>> $mydate->setDate($date, $time)
=> null
>>>
>>> $mydate->test
=> Carbon\Carbon {#681
     +"date": "2016-05-19 20:35:00",
     +"timezone_type": 3,
     +"timezone": "UTC",
   }
>>>
>>> $mydate->save()
=> true
>>>
>>> App\Mydate::first()->test->toDateTimeString()
=> "2016-05-19 20:35:00"
>>>
>>> App\Mydate::first()->test
=> Carbon\Carbon {#696
     +"date": "2016-05-19 20:35:00",
     +"timezone_type": 3,
     +"timezone": "UTC",
   }

You'd need to work out a few details like validation and such. This is just a simple example to get you started.

Please or to participate in this conversation.