Osman Rafi
Osman Rafi

Reputation: 1046

How to change values all other rows in Laravel?

I have a DB table like following

-----------------------------
id    name        featured  |
1     jhon           1      |
2     Doe            0      |
3     Mark           1      |
4     Hyk            0      |
-----------------------------

When I will change any of the featured column value 0 to 1, all other featured value will be set to 0. For instance if change the featured value where id=2, the updated table should look like

-----------------------------
id    name        featured  |
1     jhon           0      |
2     Doe            1      |
3     Mark           0      |
4     Hyk            0      |
-----------------------------

What will be the appropriate eloquent query ? Assuming the Model is Player and DB table name is players.

Laravel version: 7.30.4

Upvotes: 0

Views: 876

Answers (2)

Mitali Patel
Mitali Patel

Reputation: 161

Try with this,

$player = Player::where('id', $id)
            ->update(['featured' => 1]);

// Make sure that you have featured column datatype is tinyint or int
// if you have datatype varchar or text type you have to 
   ->update(['featured' => '1']) like this

Upvotes: 0

gemefa
gemefa

Reputation: 31

You maybe call update on all players:

Player::update(['featured' => 0]);

To update a specific Player, use a unique column like id to affect only that player,

$playerId = 2;        
Player::whereId($playerId)->update(['featured' => 1]);

Upvotes: 3

Related Questions