Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, updated_at and created_at fields are null. How make them auto-complete with current timestamps?

I insert data like this:

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

Thanks.

like image 940
el valuta Avatar asked May 03 '16 07:05

el valuta


People also ask

How do I get rid of time stamp in laravel?

You either have to declare public $timestamps = false; in every model, or create a BaseModel, define it there, and have all your models extend it instead of eloquent.

How do I save a timestamp in laravel?

By default, those pivot tables do not contain timestamps. And Laravel does not try to fill in created _at/updated _at in this situation. You can save the timestamps automatically all you need to do is to add them into migration file, and then define relationship using ->withTimestamps();

What is the use of timestamps in laravel?

Timestamps allows you to automatically record the time of certain events against your entities. This can be used to provide similar behaviour to the timestamps feature in Laravel's Eloquent ORM.


2 Answers

you have to use create method instead of insert method in laravel. Create method automatically add timestamp for created_at and updated_at field. User::create(array('name' => 'John'));

like image 111
Rakesh Nandi Avatar answered Nov 16 '22 04:11

Rakesh Nandi


You probably do not use Eloquent when inserting data, in this case you should add timestamps manually.

If you do not 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's 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()
            ]);
like image 42
Alexey Mezenin Avatar answered Nov 16 '22 04:11

Alexey Mezenin