Prashant Shukla Prashant Shukla -4 years ago 110
MySQL Question

Update table where single id have multiple records in laravel

I have a table like below.

Table A

id | id_n | val_a
1 | 1 | a1
2 | 2 | a2
3 | 2 | a3
4 | 2 | a4


and I want to update all values where
id_n = 2
with
val_a = {b1,b2,b3,b4,b5}
with using laravel 5.2

after update table look like below.

id | id_n | val_a
1 | 1 | a1
2 | 2 | b1
3 | 2 | b2
4 | 2 | b3
5 | 2 | b4
6 | 2 | b5


How can I do this in laravel 5.2? Thanks Ahead.

Answer Source

If you want to remove old records and want to update new

  1. Remove old records like this,

    DB::table('table_name')->where('id_n', 2)->delete();
    
  2. Store new records

    $postData = [
        ["id_n" => 2,"val_a"=> "b1"],
        ["id_n" => 2,"val_a"=> "b1"],
        ........
    ];
    DB::table('table_name')->insert($postData);
    
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download