Insert array in bank with Laravel


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 insert into the database as follows:

        for ($i = 0; $i < count($telefone); $i++) {

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

asked by anonymous 02.12.2015 / 13:03

1 answer


Depends on your database.

Arrays represent more than one die.

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

$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 "inserting a array into the bank" you will have to do gambiarras as json_encode :

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

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


This last example is highly recommended rsrsrs

In your case

I realize that your Laravel encoding pattern is a bit different from what I'm used to seeing.

But I believe this information is valid in all cases.

You are only inserting the last value, because to insert you into the database, you have to call the save method 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ê
02.12.2015 / 16:43