Laravel – best way to update huge amount of data from request?

  laravel, php

I have an ecommerce application developed using laravel. Every day I want to update an amount of products from external api (request).

Response:

[
  {
    "id": 1,
    "code": "0564",
    "amount": 200
  },
  {
    "id": 2,
    "code": "4235",
    "amount": 24
  },
  {
    "id": 3,
    "code": "27683",
    "amount": 646
  },
  {
    "id": 4,
    "code": "457",
    "amount": 44
  },
]

Below laravel function in controller:

public function import(Request $request)
    {
        $products = $request->all();

        foreach ($products as $product) {
            $currentProduct = Product::where('code', $product['code'])->first();
            if ($currentProduct) {
                $currentProduct->amount = $product['amount'];
                $currentProduct->update();
            }
        }

        return response()->json([
            'status' => 'success',
        ], Response::HTTP_OK);
}

Above code is working, but it is slower. Is there any best way to do this?

Source: Laravel

Leave a Reply