Created
December 16, 2020 10:38
-
-
Save eliyas5044/40cdfaf95546f2a90cff446506341710 to your computer and use it in GitHub Desktop.
Bulk insert or update in Laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// first get ids from table | |
$exist_ids = DB::table('shipping_costs')->pluck('area_id')->toArray(); | |
// get requested ids | |
$requested_ids = $request->get('area_ids'); | |
// get updatable ids | |
$updatable_ids = array_values(array_intersect($exist_ids, $requested_ids)); | |
// get insertable ids | |
$insertable_ids = array_values(array_diff($requested_ids, $exist_ids)); | |
// prepare data for insert | |
$data = collect(); | |
foreach ($insertable_ids as $id) { | |
$data->push([ | |
'area_id' => $id, | |
'cost' => $request->get('cost'), | |
'created_at' => now(), | |
'updated_at' => now() | |
]); | |
} | |
DB::table('shipping_costs')->insert($data->toArray()); | |
// prepare for update | |
DB::table('shipping_costs') | |
->whereIn('area_id', $updatable_ids) | |
->update([ | |
'cost' => $request->get('cost'), | |
'updated_at' => now() | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment