Update multiple records at once laravel

1

Hello, I have a table with the following fields: KEY, VALUE , ALIAS, CLIENT_ID . In a given system process I need to update the Key and Value.

To update the append a record I have no problems, the problem is that when I need to change two KEYS and two VALUES of a client ID I am using the update function of laravel / repositories, so the code looks like this:

 public function update(Request $request, $id)
 {
    $this->client->update($request->all(), $id);
 }

The problem is that with this method if I have 2 values and 2 keys, it overlaps the first so what I get is just

request = [ key => 'segundo valor do form', value => 'segundo valor do form'];

I need the 2 keys and the 2 values to come. Can someone help?

    
asked by anonymous 15.09.2016 / 19:37

1 answer

2

For you to submit a multi-valued form, you need to write it in the following way to make it easier to allocate the data:

{!! Form::open(array('method'=>'put', 'url' => url())) !!}

 @foreach($array as $key)
        {!! Form::text("clientes[$key][nome]", '')) !!}
        {!! Form::text("clientes[$key][endereco]", '')) !!}
        {!! Form::submit('Submit') !!}
 @endforeach 
{!! Form::close() !

!}

In the method responsible for saving the data, you could do this:

foreach  ($request->clientes as $id_key => $dados) {
    Cliente::where(['id' => $id_key])->update($dados);
}

Note that the way I declare name of the above inputs will cause PHP to generate a array like this:

[
    1 => ['nome' => 'Padaria Xodó', 'endereco' => 'Av Um - 155'],
    2 => ['nome' => 'Locadora Zezé', 'endereco' => 'Av Dois - 300']
]

So internally in foreach , you will always update the data according to id , which is the index of our array.

    
15.09.2016 / 21:11