Insert array into database with Laravel

Asked

Viewed 1,244 times

4

I have a form that returns an array with the values:

Número: {{Form::text('tel[]')}}
Proprietário: {{Form::select('proprietario[]',['Aluno'=>'Aluno','Pai'=>'Pai'])}}
Tipo: {{Form::select('tipo[]'['Pessoal'=>'Pessoal', 'Comercial'=>'Comercial'])}}

I’m trying to put it in the bank like this:

    $telefone=$_POST['tel'];    
    $proprietario=$_POST['proprietario'];
    $tipo=$_POST['tipo'];
    if(count($telefone)>0){
        for ($i = 0; $i < count($telefone); $i++) {
            $tel->numero=$telefone[$i];
            $tel->proprietario=$proprietario[$i];
            $tel->tipo=$tipo[$i];
        }
    }

The problem is that it is only inserting the last value of the array. What I am doing wrong?

  • See if in the generated html the name this one with clasps.

  • Yes, it has clasps.

  • you saw it by ctrl+u browser?

  • Yes. Displaying the page’s source code

  • you already did dd($telefone) to see what is stored?

  • Already, it is storing the data correctly in the variable. The impression I have, is that the for does not traverse the array, but I gave a echo in the $i and it’s okay.

  • What is the array of your entire collection, can make a echo '<pre>' . print_r($_POST); die(); ?

  • Yes, I can. The data is being captured by $_POST correctly.

  • tries to put a $tel->save() at the end of foreach

  • You already have @Rafaelacioly

  • @Rafaelacioly, inverti and still keeps inserting only the last record :(

  • 1

    @Amandalima seeks help in the community slack there for sure they can help you! https://laravel-br.slack.com/

  • It’s kind of weird! $_POST in Laravel?!?!? would not be Input::get?

  • $tel->tipo=$tipo[$i]; the equals signal for a normal variable within a loop, stores only one value, and they are being replaced until the last one arrives, so you only get the references of the last index of the traversed array.

Show 9 more comments

1 answer

4


Depends on your database.

Arrays represent more than one datum.

So I think the correct form would be, taking for example users and their various phones.

$dadosUsuario = Input::only('nome', 'email', 'idade');

$usuario = Usuario::create($dadosUsuario);

foreach((array) Input::get('telefones') as $telefone) 
{
      $dadosTelefone[] = [
            'usuario_id' => $usuario->id, 
            'telefone'   => $telefone

      ];
}

If you are "insert a array in the bank" will have to do gambiarras as json_encode:

 $dadosUsuario = Input::only('nome', 'email', 'idade', 'telefones');

 $dadosUsuario['telefones'] = json_encode($telefones);

 Usuario::create($dadosUsuario);

This last example is highly recommendable rsrsrs

In your case

I notice your coding pattern on Laravel is a little different than I’m used to seeing.

But I believe that this information is valid in all cases.

You are only entering the last value, because for you to enter in the bank, you have to call the method save at each iteration.

$telefone = $_POST['tel'];    

$proprietario = $_POST['proprietario'];

$tipo = $_POST['tipo'];

// Chamar o count a cada iteração é ruim

$count = count($telefone); 

if ($count > 0) {

    for ($i = 0; $i < $count; $i++) {
        $tel->numero = $telefone[$i];
        $tel->proprietario = $proprietario[$i];
        $tel->tipo = $tipo[$i];

        $tel->save(); // Salva o paranauê
    }
}
  • 2

    It was precisely the lack of save() inside the Loop, thank you very much!

  • 1

    Amanda, I know you’re not answering your question. Just for recommendation, you don’t need to use $_POST inside the Windows, you can use Input::get and for Input:file.

Browser other questions tagged

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