maxxon15 maxxon15 - 4 months ago 17
PHP Question

Inserting created_at data with Laravel

I cannot seem to insert

created_at
data in the database table with Laravel.
I'm trying to get that data from a POST request and then trying to save it to the database.

I'm currently doing like this:

$create_dt = date("Y-m-d H:i:s A", strtotime($_POST['post_date']." ".$_POST['post_time']));
$name = $_POST['name'];

$post = new Post();
$post->name = $name;
...
$post->created_at = $create_dt;
$post->save();


But an error shows up saying

Uncaught exception 'InvalidArgumentException' with message in Carbon.php


and

Unexpected data found. Unexpected data found. Data missing in Carbon.php


How do I solve this? Do I have to set
$timestamps
in my Models to false? (I really don't wanna do that because I'm fine with how it automatically inserts the
updated_at
)

Answer

In your User model, add the following line in the User class:

protected $timestamps = true;

Now, whenever you save or update a user, Laravel will automatically update the created_at and updated_at fields.


Update:
If you want to set the created at manually you should use the date format Y-m-d H:i:s. The problem is that the format you have used is not the same as Laravel uses for the created_at field.

Comments