I am having trouble using updateOrCreate.
The below code is SUCCESSFULLY creating a new row; however when it comes to updating an existing row it doesn't work at all!
comm_helpful::updateOrCreate(
['ID' => 1],
['time' => 3000]
);
This works exactly as expected:
comm_helpful::where('ID', 1)->update(['time' => 3000]);
I've stripped the examples above back to bare minimums (which I did as part of debugging) and it's still not working!!
I have a similar problem. My model had:
protected $fillable = ['user_x_cliente_id','internet_cliente_id'];
The status has 0.
$habilita = leilao_habs::updateOrCreate(
[
'user_x_cliente_id' => $user_x_cliente->id,
'internet_cliente_id' => $int_cli->id
],
['status' => 1]
);
dd($habilita);
After execute the updateOrCreate , the status still 0 and No get MassAssignmentException error.
The solution was change the model adding the status to protected $fillable:
protected $fillable = ['user_x_cliente_id','internet_cliente_id','status'];
Now the updateOrCreate works changing the status.
Ok, after almost completely pulling my hair out; I found the problem where Eloquent is setting:
protected $primaryKey = 'id';
which is used on the update method and returned by getKeyName().
protected function setKeysForSaveQuery(Builder $query)
{
$query->where($this->getKeyName(), '=', $this->getKeyForSaveQuery());
return $query;
}
I then realised my 'id' on the tale was uppercase and not lower case!
I guess that means my answer is that I need to ensure I am using lowercase 'id' for the primary key or overriding it on the Model
protected $primaryKey = 'ID';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With