w0rldart w0rldart - 15 days ago 5
MySQL Question

Laravel update mysql field with same value

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?

Answer

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();