How to improve attach bulk Laravel?

I try to attach rating to the user using many to many relation:

foreach ($rating as $value) {
    $rateduser->rates()->attach($value->rateid, ['order_id' => $order->getId(), 'user_id' => $user->getId(), 'rate' => $value->rate]);

As you can see I try to attach rate, rateid and additional data one by one. So it is exeecuted over 5 queries at time.

Is it possible to use one bulk insert request?

>Solution :

attach accept an array for mass attaching where the index is the foreign key

$toBeAttached = [];
foreach ($rating as $value) {
    $toBeAttached[$value->rateid] = ['order_id' => $order->getId(), 'user_id' => $user->getId(), 'rate' => $value->rate];
if ($toBeAttached) {

Leave a Reply