Save in two tables with dynamic inputs (one-to-Many) Laravel

Asked

Viewed 414 times

1

I couldn’t make a mistake:

Errorexception in Parameterbag.php line 88: array_key_exists(): The first argument should be either a string or an integer

My Controller:

public function store(Request $request){

  $diaria = Diaria::create($request->all());

  $diaria->trechos()->createMany($request->get([
  'local_servico',
  'local_pernoite',
  'data_afastamento_inicio',
  'hora_afastamento_inicio',
  'data_afastamento_retorno',
  'hora_afastamento_retorno',
  'adicional_deslocamento',
  'total_acrescimos',
  'ck_valor_total',
  'valor_total',
  'a_s',
  't_s',
  'houve_pernoite',
  'qt_pernoite'
]));

Session::flash('mensagem_create', 'Ordem de serviço para o Sr. ' .$request->pnome. ' foi adicionada com sucesso!');

return redirect()->route('ficha.index');

}

More details of the error:

At Handleexceptions->handleError('2', 'array_key_exists(): The first argument should be either a string or an integer', '/var/www/html/diarias/vendor/symfony/http-Foundation/Parameterbag.php', '88', array('key' => array('local_servico', 'local_pernoite', 'start_date', 'hou_start_distance', 'return data_distance', 'return hora_distance', 'addl_shift', 'total_add', 'ck_total value', 'total value', 'a_s', 't_s', 'houve_overnight', 'qt_overnight'), 'default' => Object(Request)))

A select (An example of how inputs are)

{!! Form::select('local_servico[0]', ['placeholder'=>'LOCAL DE REALIZAÇÃO DO SERVIÇO (Cidade):', 'val_br_am_rj'=>'Brasília, Manaus ou Rio de Janeiro', 'val_bh_fl_pa_rc_sl_sp'=> 'Belo Horizonte, Fortaleza, Porto Alegre, Recife, Salvador ou São Paulo', 'val_capitais'=>'Outra capital de Estado', 'val_cidades'=>'Outra Cidade'], null, ['class' => 'form-control input-sm', 'title'=>'LOCAL DE REALIZAÇÃO DO SERVIÇO (Cidade)', 'id'=>'local_servico[0]']) !!}

The others are being created with JS:

{!! Form::select('local_servico[1]',..........

Any idea?

Edited - Command return

dd($request->all());

"ne" => ""
  "em_proveito" => "UNIÃO"
  "custeio" => "SEM CUSTO"
  "tr" => array:2 [▼
    0 => array:14 [▼
      "local_servico" => "val_br_am_rj"
      "houve_pernoite" => "s"
      "qt_pernoite" => "4"
      "local_pernoite" => "cg"
      "data_afastamento_inicio" => "01/06/2017"
      "hora_afastamento_inicio" => "08:00"
      "data_afastamento_retorno" => "01/06/2017"
      "hora_afastamento_retorno" => "08:00"
      "adicional_deslocamento" => "SIM"
      "total_acrescimos" => "DIÁRIA COMPLETA"
      "valor_total" => "0"
      "ck_valor_total" => "Sem Custo"
      "t_s" => "0"
      "a_s" => "0"
    ]
    1 => array:14 [▼
      "local_servico" => "val_bh_fl_pa_rc_sl_sp"
      "houve_pernoite" => "s"
      "qt_pernoite" => "3"
      "local_pernoite" => "7"
      "data_afastamento_inicio" => "15/06/2017"
      "hora_afastamento_inicio" => "10:00"
      "data_afastamento_retorno" => "18/06/2017"
      "hora_afastamento_retorno" => "10:00"
      "adicional_deslocamento" => "NÃO"
      "total_acrescimos" => "1/2 DIÁRIA"
      "valor_total" => "4"
      "ck_valor_total" => "Sem Custo"
      "t_s" => "3"
      "a_s" => "2"
    ]
  ]
  "fim_semana" => "dgh"
  "conveniencia_servico" => "fghj"
  "justificativa" => "fgh"
    mais campos.....

in my controller I tried to save so

$diaria = Diaria::create($request->all());
 $trInput = $request->get('tr');

$tr = array();
foreach($trInput as $tr)
{
  $tr[] = new Trecho($tr);
}

$diaria->trechos()->saveMany($tr);

Example of my form:

<div id="camposAdd">
<div class="row">
    <div title="Informe a cidade de realização do serviço" class="col-md-4">
      <div class="input-group">
        <span class="input-group-addon" id="basic-addon1">19</span>
        {!! Form::select('tr[0][local_servico]', ['placeholder'=>'LOCAL DE REALIZAÇÃO DO SERVIÇO (Cidade):', 'val_br_am_rj'=>'Brasília, Manaus ou Rio de Janeiro', 'val_bh_fl_pa_rc_sl_sp'=> 'Belo Horizonte, Fortaleza, Porto Alegre, Recife, Salvador ou São Paulo', 'val_capitais'=>'Outra capital de Estado', 'val_cidades'=>'Outra Cidade'], null, ['class' => 'form-control input-sm', 'title'=>'LOCAL DE REALIZAÇÃO DO SERVIÇO (Cidade)', 'id'=>'local_servico[0]']) !!}
      </div>
    </div>
    <div class="col-md-2">
      {!! Form::input('checkbox', 'tr[0][houve_pernoite]', $value = "s", $attributes = ['id'=>'hp[0]']) !!}&nbsp&nbsp&nbspHouve Pernoite?
    </div>
    <div class="col-sm-2">
      {!! Form::text('tr[0][qt_pernoite]', null, array('id'=>'qt_pernoite[0]','class' =>'form-control input-sm', 'placeholder'=>'QNT DE PERNOITES:')) !!}
    </div>
    <div title="Informe os locais de pernoite" class="col-md-4">
      <div class="input-group">
        <span class="input-group-addon" id="basic-addon1">20</span>
        {!! Form::text('tr[0][local_pernoite]', null, array('class' =>'form-control input-sm', 'placeholder'=>'LOCAL(IS) DE PERNOITE:')) !!}
      </div>
    </div>

EDIT: I’m trying this way but it doesn’t work

    public function edit($id){

 if(!($diaria = Diaria::find($id))) {

    throw new ModelNotFoundException("Ordem de serviço não encontrada!");

  }

  $tr = $diaria->trechos;
  foreach ($tr['Trecho']['diaria_id'] as $value) {
      $tr = Trecho::find($id);
  }

return view('ficha.edit', compact('diaria', 'tr'));

}
  • How each item of trechos that’s the problem!

  • It is created via JS.. the inputs are named array: {!! Form::select('tr[0][local_servico]', .... {!! Form::input('checkbox', 'tr[0][houve_overnight]',...

  • Could you illustrate in your question!

  • The problem happens because inside the same array you have key by value and by text you should search only by value for what I could understand or else changing the name would be a good option.

  • @Virgilionovic exactly.. That’s the problem. I have to go through one array after another and save to the database while the chunk is filled in.

  • Take a test with my reply @Denis

  • @Virgilionovic notification came to the wrong Denis

  • kkkkk thanks @Virgilionovic I will take the test and I answer you!

Show 3 more comments

1 answer

0


I believe that already resolves:

$diaria = Diaria::create($request->all());
$tr     = $request->all();
foreach($tr['tr'] as $values)
{
  $diaria->trechos()->create($values);
}
  • Error! Illegal string offset 'tr'

  • I didn’t understand --> foreach($tr['ne']['tr'] as $values)

  • Now that I saw it because of a tab changes everything changed the answer, take a look! @Denisvanoni

  • mto thanks! Solved my problem..

  • Good afternoon @Virgilionovic.

  • Hi @Denisvanoni?

  • Good afternoon Virgilio, the problem now is in making the Edit of these records! Since the input numbers are not equal in the table because they are dynamic, it does not bring the records and sends them to edit view! Only the Daily table records that appear. Excerpts records do not appear because they are formatted as tr[0][local_servico].. Do you have any idea how I can bring these records? Thank you.

  • The problem is new @Denisvanoni the question is new!? understood the process! Open another question by putting this as a reference! and indicating that now is change. Ok!

  • OK @Virgilionovic

Show 4 more comments

Browser other questions tagged

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