Laravel Update multiple lines of an array

Asked

Viewed 580 times

0

I’m trying to update several lines at once, where I get the information from an array

inserir a descrição da imagem aqui

But so far I have not had much success, despite the attempts, not updating, and returning result 0

the code is currently as follows

public function atualizarEstoqueLocal($input)
{

     $resultado = [];
    foreach ($input as $result) {
        $resultado[] =  $this->produto
            ->where([['id', $result['id']], ['estoque', $result['estoque']]])
            ->update(array_except($result, 'estoque'));      

        }
        dd($resultado);
        return $resultado;

        }

would like to get a solution, know how to correct and update.

2 answers

0


Your code makes no sense. Try it like this:

public function atualizarEstoque($input)
{
    $resultado = [];
    foreach ($input as $result) {
        $resultado[] = $this->produto
            ->where([['id', $result['id']], ['estoque', $result['estoque']]])
            ->update(array_except($result, 'estoque')); 
    }

    return $resultado;
}
  • fajuchem thanks for the answer, really this way seemed more logical and better, but test this way and is returning results all 0 array:3 [ 0 => 0 1 => 0 2 => 0 ]

  • Yes, it returns the update result for each element, because in the example you sent it makes 3 updates, and it can happen that 2 are successfully performed and 1 fails,

0

I got a solution using the following code

 public function atualizarEstoque($input)
{

$resultado = [];
        foreach ($input as $result) {
            $resultado = $result;  
            //dd($resultado['id']);
            $teste = $this->produto
                ->where([['id', $resultado['id']]])
                ->update($resultado, 'estoque');
            }

            return $resultado;
}
  • The result of this function will be the last element of the array that you passed as a function parameter, I find it difficult that is what you really want.

Browser other questions tagged

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