How to use decrement in laravel 5.2 using data from an array?

1

I'm using the a few months ago and I came across the following problem of controlling inventory after purchase automatically.

The logic of my system is as follows:

After purchasing a product in my store automatically decrement the amount selected by the user at the time of purchase, the system works correctly when only one item is in the cart, when there are two items or more the system only changes one, my doubt is how the code to retrieve and manipulate all the items through an array follows the code:

file.blade.php

@foreach($produtos as $produto)
 ...
Os valores a seguir estão dentro de um input, que são enviados por um formulário (acrescentei as [] em ambos).

    <input type="hidden" name="id[]" value="{{ $produto['item']['id'] }}">
    <input type="hidden" name="qtde[]" value="{{ $produto['quantidade'] }}">
...
@endforeach

MyController.php my question is still in this file, I changed it and it looks like this:

public function funcao(Request $request)
{

DB::table('produtos')
    ->where(['id', $request->get('id')])
    ->decrement(['quantidade', $request->get('qtde')]);

}

and as expected the following error returned:

  

strtolower () expects parameter 1 to be string, array given

    
asked by anonymous 05.01.2017 / 21:39

1 answer

1

The ids and quantities will already be a server-side array, What you have to do later when you receive the data in your controller is:

...
foreach($request->get('id') as $key => $id) {
    if(isset($request->get('qtde')[$key]) && is_numeric($request->get('qtde')[$key])) {
        DB::table('produtos')
        ->where('id', $id)
        ->decrement('quantidade', $request->get('qtde')[$key]);
    }
}
...
    
06.01.2017 / 10:37