I’m trying to update a table in an SQL Server database using the Eloquent ORM, but for some reason the update is never committed. As it is a legacy database I have defined my model in the following fashion (as the table and the key do not fully adhere to the expected conventions and the timestamp columns are not named updated_at, created_at)
class User extends Eloquent {
public static $key = 'UserID';
public static $table = 'User';
public static $timestamps = false;
}
The code I’m trying to run is as simple as this:
$user = User::find($userid);
$user->password = $password;
$user->salt = $salt;
$user->resettoken = $reset_token;
$user->save();
I’ve debugged the code and can see that the User object is retrieved properly and the attributes of the User object are updated when assigned with new values. However, the save method doesn’t persist the data.
Using Fluent works like treat, though. This works for example:
$affected = DB::table('User')
->where('UserID', '=', $userid)
->update(array(
'password' => $password,
'salt' => $salt,
'resettoken' => $reset_token
)
);
But it would be nice to use Eloquent. What’s tripping me?
UPDATE: Running the code as Pierre said:
<?php
$test = new User();
die(var_dump($test));
Returns:
object(User)[39]
public 'attributes' =>
array (size=0)
empty
public 'original' =>
array (size=0)
empty
public 'relationships' =>
array (size=0)
empty
public 'exists' => boolean false
public 'includes' =>
array (size=0)
empty
The dump of the instance of the User object shows all the attributes, ie this object contains all attributes including the new values, but nothing is saved to database:
$user = User::find($userid);
$user->password = $password;
$user->salt = $salt;
$user->resettoken = $reset_token;
$user->save();
Using this syntax makes no difference:
$user = User::where_UserID($userid)->first();
Solution:
One has to use a lower case name of the key in the model, then it works.
Be sure to use lower case name of the key name in your model.
This is wrong:
This works as expected: