Nabeel Siddiqui
Nabeel Siddiqui

Reputation: 65

update multiple values having two different arrays in laravel

I am new to laravel

I have two columns in one of my table id,role_id,

and I have two arrays

$id = array(1,2,3,4,5,6,....);

$role_id = array(4,5,6,7,8,....);

what I want to do is update the role_id column according to the given id array;

for example I want role_id 4 against id 1,5 against 2

is there any way to do it in laravel

Any help will be appreciated

Upvotes: 0

Views: 277

Answers (1)

Ramisha Mukhtar
Ramisha Mukhtar

Reputation: 361

If the sizes or lengths of both the arrays are equal, then you can do it like this:

for($counter = 0; $counter< count(any of the two arrays); $counter++){
$tablename = new Tablename();
$tablename->id = $id[$counter];
$tablename->role_id = $role_id[$counter];
$tablename->save();
}

and to update:

for($counter = 0; $counter< count(any of the two arrays); $counter++){
Tablename::where('id', $id[$counter])
  ->update(['role_id' => $role_id[$counter]]);
}

Upvotes: 1

Related Questions