Laravel save() method returning true but not updating records
I had a very similar issue and this post lead me to a solution. I too was overriding a primaryKey
.
Environment:
- PHP 7.1
- Lumen 5.3 (obviously Eloquent enabled)
- Oracle 12 (using https://github.com/yajra/laravel-oci8)
SELECT
and INSERT
operations work with protected $primaryKey = 'USER_ID';
, however, UPDATE
operations did not work even though save()
returned true
.
After finding this post I changed case. protected $primaryKey = 'user_id';
, Whammy, all three operations work! I wish I had a more solid explanation why this works. When I created the table I clearly used upper USER_ID VARCHAR2(50 BYTE) NOT NULL
.
To answer the question in the title:
$user = \App\User::find(1);
$boolean = $user->save();
This will return true. Save always returns true, unless update or save did not succeed (because user_id is not found or something like this). Its not checked if an attribute has been changed. To see if an attribute has been changed see Laravel check if updateOrCreate performed update
Here is a bit of a Laravel eloquent Model.php :
// If the model already exists in the database we can just update our record
// that is already in this database using the current IDs in this "where"
// clause to only update this model. Otherwise, we'll just insert them.
if ($this->exists) {
$saved = $this->isDirty() ?
$this->performUpdate($query) : true;
}
// ...
return $saved;
isDirty()
is true if model attribute has been changed and not saved. So if isDirty()
is false, model will be not updated and return true.
This line in the Opportunity model fixed the issue.
Protected $primaryKey = "opportunityID";
Although it is difficult to understand why it was still possible to retrieve the data and create a new record.