Chiffer101
Chiffer101

Reputation: 51

Laravel updateOrCreate function does not update custom timestamp

I am using updateOrCreate function to create new rows or update exists base on given values. But when I try to update a value that defined as a timestamp (not the default "created_at" or "updated_at") it does not update the value.

The issue happens only when I use the updateOrCreate function and only when the only field to update is the timestamp field. (In my case, 'last_scan'). When I change the 'status' to 0 for example, all the values updated in the database, include the 'last_scan' field.

I want to verify that every time I run this function, last_scan updated to the time the function ran whether if there is data to update or not.

$categoryEntity = CategoryEntity::updateOrCreate(
    [
        'store_id'  => $this->store_id,
        'remote_id' => $collection->id
    ],
    [
        'remote_parent_id'  => 0,
        'name'              => $collection->title,
        'status'            => 1,
        'last_scan'         => Carbon::now()
    ]
);

I tried to replace the update and create with regular update method as following and it's worked perfect:

$categoryEntity->last_scan = Carbon::now();
$categoryEntity->save();

My migration file is as following:

Schema::create('categories_entities', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('store_id');
            $table->integer('remote_id');
            $table->integer('remote_parent_id');
            $table->string('name');
            $table->integer('status');
            $table->timestamp('last_scan');
            $table->timestamps();
});

Upvotes: 2

Views: 5162

Answers (2)

Chiffer101
Chiffer101

Reputation: 51

TL;DR

The "protected $fillable" attribute in the Model didn't contain the 'last_scan' field.

More in deep

After a little search, I notice that the createOrUpdate method use mass update functionality. The $fillable attribute must contain all the fields that we would like to provide an option to mass change them.

I looked again on the Model and noticed that the protected $fillable attribute there contained all the fields except the 'last_scan'.

Was:

protected $fillable = ['store_id', 'remote_id', 'remote_parent_id', 'name', 'status'];

Now:

protected $fillable = ['store_id', 'remote_id', 'remote_parent_id', 'name', 'status', 'last_scan'];

Upvotes: 3

MyLibary
MyLibary

Reputation: 1771

In your CategoryEntity model file, add the following property:

/**
 * The attributes that should be mutated to dates.
 *
 * @var array
 */
protected $dates = [
    'last_scan',
];

Does it work for you?

Upvotes: 2

Related Questions