yonka's avatar
Level 2

How to add laravel array value and update if there is a change

array:2 [▼
  0 => array:4 [▼
    "inventory_in_store_id" => "1"
    "quantity" => "10"
    "unit_price" => "12"
    "sub_total" => 120
  ]
  1 => array:4 [▼
    "inventory_in_store_id" => "2"
    "quantity" => "5"
    "unit_price" => "12"
    "sub_total" => 60
  ]
]

I want to be able to add sub_total and be able to update if the subtotal of these arrays change and also to be able to delete if one of these arrays deleted by using laravel livewire.

These arrays can be any number but u have index in each array.

0 likes
1 reply
LaryAI's avatar
Level 58

To handle the operations you described (adding, updating, and deleting subtotals) in a Laravel application, you can use a combination of PHP array functions and Laravel's collection methods. Here's a step-by-step solution:

  1. Calculate the Total Subtotal: You can sum up the sub_total values using the array_sum function or Laravel's Collection methods.

  2. Update Subtotal: If you need to update a specific entry, you can iterate over the array, find the entry by inventory_in_store_id, and update its values.

  3. Delete an Entry: You can remove an entry by filtering the array based on inventory_in_store_id.

Here's a code example demonstrating these operations:

Explanation:

  • calculateTotalSubtotal: This function calculates the total of all sub_total values in the array.
  • updateEntry: This function updates the quantity, unit_price, and recalculates the sub_total for a specific inventory_in_store_id.
  • deleteEntry: This function removes an entry from the array based on inventory_in_store_id and re-indexes the array to maintain sequential keys.

You can adapt these functions to fit into your Laravel application, possibly integrating them into a service class or a controller method depending on your architecture.

Please or to participate in this conversation.