Devid
Devid

Reputation: 84

created_at and updated_at not working automatically in laravel 5.6 when use model::insert() . why?

ProductCategory::insert($insertData);

I am using this above statement passing an array for inserting multiple record $insertData working fine but when check my created_at and updated_at column not getting timestamp.

Upvotes: 3

Views: 11807

Answers (3)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25916

You have to use create() (remember to set $fillable):

foreach($insertData as $data) {
    ProductCategory::create($data);
}

Upvotes: 6

Jagjeet Singh
Jagjeet Singh

Reputation: 1572

You need to use Laravel Eloquent feature to make timestamps written to the Database automatically, when you insert data directly, Laravel does not know about your timestamps. You need to set the timestamps manually in the insert statement.

Use Eloquent models, like following :-

foreach($insertData as $data) {
 ProductCategory::create($data);
}

Eloquent ORM

Upvotes: 1

Jason Grim
Jason Grim

Reputation: 413

The insert() method is a direct SQL statement by the QueryBuilder. It converts your array of values into a query statement to insert without mutators or other magic.

You can do a couple things to set these values. You can loop through an do a single insert for each row of data using ProductCategory::create($array);. Which will do a query per insert.

Or you can add the created_at and updated_at values to your array collection directly. Laravel has a method built in to set the updated at column on an array \Illuminate\Database\Eloquent\Builder::addUpdatedAtColumn() if you wanted to loop through $insertData and set it. If you look at it you'll see it just applies to the updated_at column. You need the created_at value too.

I would recommend you doing something like this if you wish to keep a single insert statement:

$object = new ProductCategory();
$insertData = array_map(function ($data) use ($object) {
    $timestamp = $object->freshTimestampString();
    $data[$object->getUpdatedAtColumn()] = $timestamp;
    $data[$object->getCreatedAtColumn()] = $timestamp;
    return $data;
}, $insertData);
$object->insert($insertData);

Upvotes: 1

Related Questions