Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting created_at data with Laravel

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)

like image 203
maxxon15 Avatar asked Oct 22 '14 11:10

maxxon15


People also ask

Which method is used to insert records in the table in laravel?

We can insert the record using the DB facade with insert method.


2 Answers

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.

like image 199
Jerodev Avatar answered Sep 18 '22 09:09

Jerodev


You can manually set this using Laravel, just remember to add 'created_at' to your $fillable array:

protected $fillable = ['name', 'created_at'];  
like image 36
Sabrina Leggett Avatar answered Sep 22 '22 09:09

Sabrina Leggett