Reputation: 7688
How can I update a record in Laravel, to its same value as before.
Have tried the following, but it didn't work, and I wouldn't want to do another query to get the value and set it.
$user = User::update($edit['id'], array(
'name' => $edit['username'],
'email' => $edit['email'],
'password' => (is_null($edit['password']) ? '`password`' : Hash::make($edit['password'])),
));
Any ideas?
Upvotes: 0
Views: 4124
Reputation: 219936
That's what DB::raw()
is for:
$user = User::where_id($edit['id'])::update([
'name' => $edit['username'],
'email' => $edit['email'],
'password' => empty($edit['password']) ? DB::raw('`password`') : Hash::make($edit['password'])
]);
Even better would be to just not set it in the array:
$update_info = [
'name' => $edit['username'],
'email' => $edit['email']
];
if (! empty($edit['password'])) {
$update_info['password'] = Hash::make($edit['password']);
}
$user = User::where_id($edit['id'])::update($update_info);
If User
is an Eloquent
model, try this:
$user = User::find($edit['id']);
$user->username = $edit['username'];
$user->email = $edit['email'];
if (! empty($edit['password'])) {
$user->password = Hash::make($edit['password']);
}
$user->save();
Upvotes: 3
Reputation: 4888
I wanted to do the same thing for a project i was working on. I know I got it working, I think this is how:
User::where('id','=',$edit['id'])->update( array(
'name' => $edit['username'],
'email' => $edit['email'],
'password' => is_null($edit['password']) ? DB::raw('`password`') : Hash::make($edit['password'])
));
Upvotes: 4