I can't seem to insert created_at
data in the database table with Laravel.
I'm trying to get that data from a POST 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 it gives an error:
Uncaught exception 'InvalidArgumentException' with message in Carbon.php
and
Unexpected data found. Unexpected data found. Data missing in Carbon.php
How can I solve this? Do I need to set $timestamps
in my Models to false? (I really don't want do that because I'm fine with how it automatically inserts the updated_at
)
In your User
model, add the following line in the User
class:
public $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.
Update: Nov 2018 Laravel 5.6
"message": "Access level to App\\Note::$timestamps must be public",
Make sure you have the proper access level as well. Laravel 5.6 is public
.
You can manually set this using Laravel, just remember to add 'created_at' to your $fillable array:
protected $fillable = ['name', 'created_at'];
In my case, I wanted to unit test that users weren't able to verify their email addresses after 1 hour had passed, so I didn't want to do any of the other answers since they would also persist when not unit testing, so I ended up just manually updating the row after insert:
// Create new user
$user = factory(User::class)->create();
// Add an email verification token to the
// email_verification_tokens table
$token = $user->generateNewEmailVerificationToken();
// Get the time 61 minutes ago
$created_at = (new Carbon())->subMinutes(61);
// Do the update
\DB::update(
'UPDATE email_verification_tokens SET created_at = ?',
[$created_at]
);
Note: For anything other than unit testing, I would look at the other answers here.
Currently (Laravel 5.4) the way to achieve this is:
$model = new Model();
$model->created_at = Carbon::now();
$model->save(['timestamps' => false]);
$data = array();
$data['created_at'] =new \DateTime();
DB::table('practice')->insert($data);
Source: Stackoverflow.com