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

Asked

Viewed 104 times

1

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

The logic of my system is this::

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

php.blade.

@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

Meucontroller.php my doubt is still in this file, I altered and it’s like this:

public function funcao(Request $request)
{

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

}

and as already expected returned the following error:

strtolower() expects Parameter 1 to be string, array Given

  • Shows the form inputs in full sff

  • The error is there you must send an array, name="id[]" and the same to the Qtd, after the server side you work it in a foreach

  • Okay, thanks for responding so quickly, could you give me some example of what the code looks like?

1 answer

1


The ids and quantities will already be a server-side array, What you have to do afterwards 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]);
    }
}
...
  • Thank you very much, it worked perfectly!

  • No @jardelfrank, I’m glad I helped. Mark the answer as accepted sff, below the top/bottom arrows to the left of the answer

  • I was really looking for where to do this, the first time I ask questions here and I hope to return soon : ) thanks again!

  • Welcome Hehe @jardelfrank

Browser other questions tagged

You are not signed in. Login or sign up in order to post.