skip to Main Content

I have an array list of data I want to update to the inventory table.

              $data['items'] = DB::table('inventory_items')->select('inventory_items.*')
                ->join('sorder_parts', 'inventory_items.id', 'sorder_parts.inventory_id')
                ->where('sorder_parts.sorder_id', '=', $id)
                ->selectraw('inventory_items.quantity - sorder_parts.quantity AS new_quantity')
                ->get()->toArray();

            foreach ($data as $product_item) {
                $reduce_quantity = InventoryItem::updateOrCreate(['id' => $product_item['items']['id']],
                ['quantity' => $product_item['quantity']['new_quantity']]);      
            }

3

Answers


  1. Probably $product_item variable does not have items key. Try to change "$product_item[‘items’][‘id’]" to "$product_item[‘id’]".

    Because "DB" facade with get() method does not return a deep array.

    Login or Signup to reply.
  2. Try this

    $data['items'] = DB::table('inventory_items')
        ->select('inventory_items.*')
        ->join('sorder_parts', 'inventory_items.id', '=', 'sorder_parts.inventory_id')
        ->where('sorder_parts.sorder_id', '=', $id)
        ->selectRaw('inventory_items.id, inventory_items.quantity - sorder_parts.quantity AS new_quantity')
        ->get();
    
    foreach ($data['items'] as $product_item) {
        InventoryItem::updateOrCreate(
            ['id' => $product_item->id], // Use $product_item->id instead of $product_item['items']['id']
            ['quantity' => $product_item->new_quantity] // Use $product_item->new_quantity instead of $product_item['quantity']['new_quantity']
        );
    }
    
    Login or Signup to reply.
  3. Maybe you didn’t define $fillable property in the InventoryItem model.

    So first of all, check your model and make sure you defined $fillable in it.

    If it’s defined, try debugging $reduce_quantity using the dd() or Log::info() function like below,

    foreach ($data as $product_item) {
        $reduce_quantity = InventoryItem::updateOrCreate(['id' => $product_item['items']['id']],
             ['quantity' => $product_item['quantity']['new_quantity']]);     
        Log::info($reduce_quantity);
    }
    

    check your log file and see what the output is.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search