Adam Winster
Adam Winster

Reputation: 69

Update statement with custom variable using laravel

I'm trying to run an update statement using the following code:

DB::update('update users set elo = 44 where id = 10 limit 1', array(1));

This works fine, however I want to pass in a custom variable into the id instead of '10'. For example:

DB::update('update users set elo = 44 where id = $homeplayer limit 1', array(1));

However I don't think this is the correct way to do it as it is not working. Could anyone point me in the right direction?

Thanks!

Upvotes: 0

Views: 3347

Answers (3)

Namoshek
Namoshek

Reputation: 6544

As far as I know, the following two options should both work:

$id = 10; // make sure we have an id

DB::statement(DB::raw('update users set elo = 44 where id = ? limit 1', [$id]));

DB::statement(DB::raw('update users set elo = 44 where id = :id limit 1', ['id' => $id]));

although the following would be a bit more "eloquent"...

$id = 10; // make sure we have an id

User::where('id', $id)->update(['elo' => 44]);

Edit: Please be aware that all of the above solutions will not fire any Eloquent events in case of an update. If you want such an event to be fired, you'll have to perform an update like so

$user = User::find($id);
$user->elo = 44;
$user->save();

Upvotes: 1

Vasyl Sovyak
Vasyl Sovyak

Reputation: 519

DB::table('users')->where('id', 10)->update(['elo' => 44]);
DB::table('users')->where('id', 10)->limit(1)->update(['elo' => 44]);
DB::update('update `users` set `elo` = ? where `id` = ?', [44, 10]);

Upvotes: 1

Ali
Ali

Reputation: 3666

you can use the following:

DB::table('users')->where('id', $homeplayer)->update(['elo' => 44]);

check out the official documentation about query builder

Upvotes: 0

Related Questions