Timestamps (updated_at, created_at) are null in Laravel 5

I have a problem with updated_at , created_at fields in Laravel 5.

Here is my migration:

 Schema::create('lots', function (Blueprint $table) { $table->increments('id'); $table->integer('lot'); $table->integer('is_active'); $table->timestamps(); }); 

But when I insert some data into this table, the updated_at and created_at fields are null. How to make them autocomplete with current timestamps?

I insert the data as follows:

 \DB::table('admin_lots')->insert([ 'lot' => $request->cycle_lot, 'is_active' => '1', ]); 

Thanks.

+7
source share
5 answers

You are probably not using Eloquent when inserting data, in which case you should add timestamps manually.

If you don’t want to do this, but you still need filled timestamps, use this hack :

 $table->timestamp('created_at')->default(\DB::raw('CURRENT_TIMESTAMP')); $table->timestamp('updated_at')->default(\DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')); 

Update

Based on your updated code, here is another solution:

 \DB::table('admin_lots')->insert([ 'lot' => $request->cycle_lot, 'is_active' => '1', 'created_at' = \Carbon\Carbon::now()->toDateTimeString(), 'updated_at' = \Carbon\Carbon::now()->toDateTimeString() ]); 
+5
source

When you enter data directly, Laravel will not know about your timestamps. You can manually set timestamps in the insert statement, or switch to using Eloquent models that handle many things out of the box for you, including timestamps. It also facilitates maintenance than direct inquiries where applicable.

Eloquent ORM

+5
source

Check if your model has this line.

 public $timestamps = false; 

If it is, delete it.

+4
source

You need to use Laravel awesome Eloquent to automatically create timestamps written to the database ...

As you can see, your example code for the eloquent will look like this:

 $lot_inputs = array( 'lot' => $request->cycle_lot, 'is_active' => 1 ); $new_lot = Lot::create($lot_inputs); 

Note that you have a model for the table = 'lots' (and it should extend Eloquest) so you can easily use the Eloquent methods and its properties ...

It would be great if you make the most of Eloquent ORM so that in the future you want to change your database technology, then you won, you do not need to specify written eloquent queries again (for example: converting a query into different database languages ​​is automatically performed by Eloquent)

Thank you, I hope this helps you solve your problem .. !!

+1
source

You should use the create method instead of the insert method in laravel. The create method automatically adds a timestamp for the selected_at and updated_at fields. User::create(array('name' => 'John'));

0
source

All Articles