Reputation: 67
I am using the updateOrCreate()
function to update the record if a record is already available in the table based on some condition. However, I do not want to update one of my columns that contains a unique value.
I want to perform the same action to this column like created_at
is working
while creating the records value is adding to the created_at
column but while updating it contains the same.
To prevent this issue I removed that column name from $fillable
in my model. But, in this case, it is not adding any value to this column.
protected $fillable = ['uid', 'channel', 'updated_at'];
$data = [
'uid' => Helper::generateUid(),
'channel' => $info['channel'],
'created_at' => time(),
'updated_at' => time(),
];
$cond = ['channel' => $info['channel']];
$isAdded = Templates::updateOrCreate($cond, $data);
Expected result I don't want to update uid column if details already there.
Actual result If details are not there it adds value to uid column and other columns also and if details are available then also it is updating uid column.
Upvotes: 1
Views: 1140
Reputation: 62228
You can't do that with the updateOrCreate
method. You'll need to be slightly more explicit. You can use the firstOrNew
method to retrieve or instantiate a new object. And then you can use the exists
property to determine if it is an existing or new object.
$template = Templates::firstOrNew(['channel' => $info['channel']]);
if (!$template->exists) {
$template->uid = Helper::generateUid();
}
$template->save();
I left out the created_at
and updated_at
fields because they are automatically handled by Laravel.
Upvotes: 1