user3413723
user3413723

Reputation: 12233

Update Created_at timestamp Laravel db seeding

I'm running an app that processes user data entered over a period of time. For that, I need to change the timestamps in the data I use to seed the database. I have a nice loop to do it, but the problem is, when I run the database seeding, nothing happens. I'm wondering if there is a Laravel specific thing that prevents this, and if so how to get around it.

            $record->created_at = $fakeCreateDate->format('Y-m-d H:i:s');
            $record->save();

Upvotes: 2

Views: 8157

Answers (2)

user985366
user985366

Reputation: 1699

The Carbon::now() method can help you here.

In your example, it should work with

$record->created_at = \Carbon\Carbon::now()
$record->save()

If you need to do an insert with DB::table, for example to update the date, you need to use the right method to create the date.

Let's say you have a table things with only id and timestamps like this Schema

$table->increments('id');
$table->timestamps();

One example of a date update is:

DB::table('things')->insert(['created_at' => \Carbon\Carbon::now()]);

Upvotes: 2

Christopher Pecoraro
Christopher Pecoraro

Reputation: 136

Yes, created_at and updated_at are "special". Laravel sets the timestamp for created_at at create time and updated_at at update time.

http://laravel.com/docs/eloquent#timestamps

You can turn them off by doing this inside your model

public $timestamps = false;

By default, Eloquent will maintain the created_at and updated_at columns on your database table automatically. Simply add these timestamp columns to your table and Eloquent will take care of the rest. If you do not wish for Eloquent to maintain these columns, add the following property to your model

Once a model is defined, you are ready to start retrieving and creating records in your table. Note that you will need to place updated_at and created_at columns on your table by default. If you do not wish to have these columns automatically maintained, set the $timestamps property on your model to false.

Upvotes: 2

Related Questions