0

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?

Alex
  • 7,538
  • 23
  • 84
  • 152

2 Answers2

3

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();
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
  • None of the solutions proposed work. 1st one, simply does the same as before and the 2nd one return a `Cannot use a scalar value as an array` message – Alex Jan 17 '13 at 19:12
  • @w0rldart - Is `User` an eloquent model? – Joseph Silber Jan 17 '13 at 19:15
  • Yes, it is `class User extends Eloquent` – Alex Jan 17 '13 at 19:19
  • @w0rldart - ...and the first example gives you no error? That's weird. AFAIK `::update` is only used in the Fluent Query Builder. Eloquent wants you to `::find` by id, then set properties on that. – Joseph Silber Jan 17 '13 at 19:21
  • 1
    @w0rldart - You haven't specified your requirement for the password. Now that I understand what you're doing, I'd advise you to use [`empty`](http://php.net/manual/en/function.empty.php) (though that'll also prevent `0` from passing. Your choice). I updated my answer accordingly. – Joseph Silber Jan 18 '13 at 15:09
3

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'])
));
Blessing
  • 4,858
  • 1
  • 18
  • 13