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

lkmadushan's avatar

Laravel create a new record using Input::all() with date fields.

How to convert all the date fields in the Input::all() to date format and insert to the database using Model::create(Input::all());

0 likes
6 replies
brayniverse's avatar
Level 5

Eloquent has a method called getDates which returns an array of the database columns that need to be converted to dates when creating / saving.

class MyModel extends Eloquent {
    public function getDates()
    {
        return array('my_date_field', 'created_at', 'updated_at');
    }
}

source

By using this you can automatically convert date fields using Model::create(Input::all()).

1 like
brayniverse's avatar

I just noticed that the getDates method actually merges a variable $this->dates which you can use instead.

class MyModel extends Eloquent {
    protected $dates = ['my_date_field'];
}

You wouldn't need to set the created_at or updated_at date columns here because the getDates method will merge them behind the scenes.

2 likes
MThomas's avatar

A question can getDates() also be used to transform the dates that are not in the mysql datetime format to the proper format?

brayniverse's avatar

The method that converts your date to a Carbon date is here.

I thought $this->getDateFormat() would return some configurable date format but it doesn't seem to. So the answer to your question depends on what this line does. If you can configure the value returned from getDateFormat then you can convert whatever date format is given to fromDateTime.

Please or to participate in this conversation.