Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplifying Laravel's updateOrCreate method for updating multiple rows

I'm using updateOrCreate to update multiple rows. This could get ugly. Is there a smart way to simplify this or does the method provide a way to save multiple rows?

RequestData::updateOrCreate(['r_id' => $rid, 'meta_key' => 'q1'], ['meta_value' => Input::get('q1')]);
RequestData::updateOrCreate(['r_id' => $rid, 'meta_key' => 'q2'], ['meta_value' => Input::get('q2')]);
RequestData::updateOrCreate(['r_id' => $rid, 'meta_key' => 'q3'], ['meta_value' => Input::get('q3')]);
RequestData::updateOrCreate(['r_id' => $rid, 'meta_key' => 'q4'], ['meta_value' => Input::get('q4')]);
RequestData::updateOrCreate(['r_id' => $rid, 'meta_key' => 'q5'], ['meta_value' => Input::get('q5')]);
like image 627
Klav Avatar asked Dec 06 '25 09:12

Klav


1 Answers

You can always wrap it in a for loop. Wrapping the whole thing in a transaction speeds things up as well.

\DB::transaction(function() use ($rid) {
    for($i = 1; $i <= 5; $i++) {
      RequestData::updateOrCreate(['r_id' => $rid, 'meta_key' => "q$i"], ['meta_value' => Input::get("q$i")]);
    }
});
like image 151
Pepijn Olivier Avatar answered Dec 08 '25 22:12

Pepijn Olivier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!